这是我对猫鼬的自定义验证器。是否有更方便的方法对一个字段进行多重验证?它有效,但我认为这不是最好的方式。我通过本机mongoose验证器进行多重验证的所有尝试都已崩溃。
schema.pre('save', function(callback) {
var self = this;
function nameLength (){
var Regex1 = /^.{4,12}$/;
if (Regex1.test(self.username)=== false){
return(" Username must be between 4 and 12 characters long");
}else{
return(0);
}
}
function nameSymbols () {
var Regex1 = /^[A-Za-z0-9]+$/;
if (Regex1.test(self.username) === false) {
return (" Only roman letters and numbers can be used");
} else {
return (0);
}
}
function passwordLength (){
var Regex1 = /^.{8,50}$/;
if (Regex1.test(self.password)=== false){
return("Password must be between 8 and 50 characters long");
}else{
return(0);
}
}
var f1 = nameLength();
var f2 = nameSymbols();
var f3 = passwordLength();
var val = {};
val.checkUsername = [f1, f2].filter(function(string){return string});
val.checkPassword = [f3].filter(function(string){return string});
if(val.checkUsername.length == 0){
delete val.checkUsername
}else if((val.checkPassword.length == 0)){
delete val.checkPassword
};
for(var key in val){
console.log(key);
if(key){
var err = new RegError(val);
callback(err);
}else{
callback();
}
}
});
答案 0 :(得分:0)
根据你的目的,我会说你的方法很好。我所做的唯一调整将与风格有关(它可能更简洁)。
但是,您的代码中存在一个突出的缺陷:
如果用户名正确,则永远不会检查密码规则。因此,即使密码是corect,密码也会调用您的回调错误。
if (val.checkUsername.length == 0) {
delete val.checkUsername
}
if ((val.checkPassword.length == 0)) {
delete val.checkPassword
}