首页 > 解决方案 > 验证器在反应中向表单寄存器抛出错误请求

问题描述

我正在使用 redux 制作一个反应应用程序,用户需要注册和登录并需要填写表格。我已经使用 isempty 实现了表单验证。但是,当我使用验证运行代码时,它会返回错误的请求 {} 错误。无需验证即可正常工作。

这是我的验证文件:

注册.js


const Validator = require('validator');
const isEmpty = require('./isempty');

module.exports = function validateRegisterInput(data){
  let errors ={};


  if (!Validator.isLength(data.name, {min: 3, max: 30})){
    errors.name = 'Name must be between 3 and 30 characters';
  }

  if (isEmpty(data.name)){
    errors.name = 'Name is required';
  }

  if (!Validator.isEmail(data.email)){
    errors.email = 'Email is invalid';
  }

  if (isEmpty(data.email)){
    errors.email = 'Email is required';
  }
  if (!Validator.isLength(data.password, {min: 6, max: 30})){
    errors.password = 'Password must be between 6 and 30 characters';
  }

  if (isEmpty(data.password)){
    errors.password = 'Password is required';
  }

  if (isEmpty(data.password2)){
    errors.password2 = 'Confirm Password is required';
  }

  if (!Validator.equals(data.password, data.password2)){
    errors.password2 = 'Passwords must match';   
  }
  

  return {
    errors,
    isValid: isEmpty(errors)
  }
}

是空的 Js :

const isEmpty = value => 
    value === undefined ||
    value === null ||
    (typeof value === "Object" && Object.keys(value).length === 0) ||
    (typeof value === "string" && value.trim().length === 0)


module.exports = isEmpty;

API调用:

_route.post('/register',(req,res) => {

   const {errors, isValid} = validateRegisterInput(req.body);
  
  if(!isValid){
    return res.status(400).json(errors);
  }
      
      
        User.findOne({email: req.body.email})
          .then(user => {
            if (user){
              return res.status(400).json({email: 'Email already exists'});
            } else {
      
              const avatar = gravatar.url(req.body.email, {
                s: '200',
                r: 'pg',
                d: 'mm'
              });
      
              const newUser = new User({
                name: req.body.name,
                lastname: req.body.lastname,
                email: req.body.email,
                password: req.body.password,
                avatar
              });
      
              bcrypt.genSalt(10, (err, salt) => {
                if(err) throw err;
                bcrypt.hash(req.body.password, salt, (err, hash) => {
                  if (err) throw err;
                  newUser.password = hash;
                  newUser.save()
                    .then(user => res.json(user))
                    .catch(err => console.log(err))
                    logger.info(`User successfully created id: email:`)
                });
              });
            }
          })
          .catch(err => console.log(err));
      });
      

可能是什么问题?

标签: javascriptreactjsvalidationreact-redux

解决方案


推荐阅读