Installation of koa – bouncer

npm i koa-bouncer -S

use

  • html
<form action="/user" method="post">User name:<input type="text" name='username'> <br>
    <! -- <input type="email" name='email'> <br> -->Password:<input type="password" name='pwd1'> <br>Confirm password:<input type="password" name='pwd2'> <br>
    <input type="submit" value="Submit"><br>
</form>
Copy the code
  • Use middleware in the entry JS file
// Register koa-bouncer to provide some help for CTX
const bouncer = require('koa-bouncer');
app.use(bouncer.middleware());
Copy the code
  • user.js
// Form validation
const bouncer = require('koa-bouncer');
router.post('/'.async (ctx, next) => {
    // ctx.request.body
    // username password
    try {
        // Use the methods provided by the middleware
        ctx.validateBody('username')
            .required('Username is required') // Only the username field is required, which can be null
            .isString() // Make sure the input field is a string, or can be converted to a string
            .trim() // Remove the space before and after
            .isLength(6.12.'Username must be 6-12 digits') // Limit the length

        ctx.validateBody('email')
            .optional()
            .isString()
            .trim()
            .isEmail('Illegal email format')

        ctx.validateBody('pwd1')
            .required('Password is mandatory')
            .isString()
            .isLength(6.16.'Password must be 6 to 16 characters')

        ctx.validateBody('pwd2')
            .required('Password is mandatory')
            .isString()
            .eq(ctx.vals.pwd1, 'Two different passwords')

        // Check whether the database has the same value
        // ctx.validateBody('username')
        // .check(await db.findUserByUsername(ctx.vals.username),'Username taken')
        // ctx.validateBody('username').check(' Tom ', 'username already exists ')

        // If the code executes at this point, the verification passes
        // The validator populates the · ctx.VALS · object with the purified values
        console.log(ctx.vals);

        ctx.body = {
            ok: 1}}catch (error) {
        // Check exception special judgment
        if (error instanceof bouncer.ValidationError) {
            ctx.status = 400
            ctx.body = 'Verification failed :' + error.message;
            return;
        }
        throw error
    }
})
Copy the code