2017-12-30 33 views
0

私はexpress-validatorを使用しています。validationResultでexpress-validatorを使用してフィールドが空のときにエラーを生成する方法

フィールドが空の場合、validationResultでエラーを生成します。

これは私のコードです:

router.post('/register',[ 
    check('name').isEmpty().withMessage('Name field cannot be empty.'), 
    check('email').isEmail().withMessage('Enter valid email address.'), 
    check('username').isEmpty().withMessage('Username cannot be empty.'), 
    check('password').isEmpty().matches('password2').withMessage('Password dont match.') 
], function(req, res, next) { 

    const errors = validationResult(req); 
    console.log(errors.array()); 

    if (!errors.isEmpty()) { 
    res.render('register2',{ 
     errors: errors.mapped(), 
     name: req.body.name, 
     email: req.body.email, 
     username: req.body.username, 
     password: req.body.password, 
     password2: req.body.password2 
    }); 
    } 
}); 

私は名前フィールドとユーザー名フィールドが空の場合、エラーを生成したいが、私は唯一のこれらのフィールドのエラーを取得:

[ { location: 'body', 
param: 'email', 
value: '', 
msg: 'Enter valid email address.' }, 
{ location: 'body', 
param: 'password', 
value: '', 
msg: 'Password dont match.' } ] 

答えて

1

あなたは現在、反対をしていますあなたが望むもののこれを行うとき:

check('username').isEmpty().withMessage('Username cannot be empty.'), 

あなたはユーザー名を空にし、そうでない場合はエラーを出します。

check('username').not().isEmpty().withMessage('Username cannot be empty.'), 

か:あなたはそれを変更することができます

check('username').exists().withMessage('Username cannot be empty.'), 

を代わりに。

+0

.not()が機能しました。ありがとう。 – Addictd

関連する問題