我只是学习节点MVC模式。我创建了一个Validation类来验证用户数据。
class UserValidation {
constructor() {}
emailAddressValidation(email) {
console.log(email);
const regularExpression =
/^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return regularExpression.test(email.toLowerCase());
}
passwordValidation(password) {
const regularExpression =
/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
}
loginValidation(req, res, next) {
const { email, password } = req.body;
console.log(email);
this.emailAddressValidation('addad');
// try {
// if (
// this.emailAddressValidation(email) &&
// this.passwordValidation(password)
// ) {
// next();
// } else {
// throw new Error(
// 'All fields are Required.email,password.Password should be alpha numeric.'
// );
// }
// } catch (error) {
// res.status(400).json({ err: 1, message: error.message });
// }
}
NewUserValidation(req, res, next) {
const { name, email, password, address, skills } = req.body;
try {
if (
name &&
this.emailAddressValidation(email) &&
this.passwordValidation(password) &&
address.length > 0 &&
skills.length > 0
) {
next();
} else {
throw new Error(
'All fields are required.Name,email,password,Address,Skills.Password should be alphanumeric.'
);
}
} catch (error) {
res.status(400).json({ err: 1, message: error.message });
}
}
}
export default new UserValidation();
像这样在我的路由中使用
router.post('/login', UserValidation.loginValidation);
但是我不知道为什么我得到这个错误
TypeError: Cannot read property 'emailAddressValidation' of undefined
this
将引用该类的一个实例。您必须初始化一个UserValidation
的对象,并在该对象上调用loginValidation
。像这样:
const validator = UserValidation()
router.post('/login', validator.loginValidation);