#javascript #reactjs #validation #react-redux
Вопрос:
Я создаю приложение react с redux, в котором пользователю необходимо зарегистрироваться и войти в систему, а также заполнить форму. Я реализовал проверку формы с помощью isempty . Однако, когда я запускаю код с проверкой, он возвращает ошибку bad request {}. Это прекрасно работает без проверки.
Вот мой файл проверки :
Register.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" amp;amp; Object.keys(value).length === 0) ||
(typeof value === "string" amp;amp; 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));
});
What could be the issue?