[AppleScript] 纯文本查看 复制代码
var validate = (function(){
var instructions = {
notEmpty:"不能为空!",
isPhone:"手机号不正确!"
};
var types = {
notEmpty:function(value){
if(value==null||value.length===0){
return false;
}
return true;
},
isPhone:function(value){
var reg = /\\d+/;
if(reg.test(value)){
return true;
}
return false;
}
}
return function(value,type){
//type为检测类型,value为检测的值
if(!types[type]){
throw "检测类型不存在";
}
if(!types[type](value)){
return instructions[type];
}
return false;
}
})();
//测试
console.log(validate("","notEmpty"));
// "不能为空!"
[AppleScript] 纯文本查看 复制代码
//返回多个检测的结果,如果验证都通过则返回空的数组
var detect = function(value,types){
var result = [];
if(!(types instanceof Array)){
//这里只是做类型检测,万一手贱输错了就不好了
throw "检测类型需要为数组不正确";
}
for(var type of types){
var msg = validate(value,type);
if(msg){ //如果信息存在
result.push(msg);
}
}
return result.length?result:false;
}
console.log(detect("",["notEmpty"]));
[AppleScript] 纯文本查看 复制代码
//总的代码如下,如果有兴趣可以拷贝测试一下。
var validate = (function(){
var instructions = {
notEmpty:"不能为空!",
isPhone:"手机号不正确!"
};
var types = {
notEmpty:function(value){
if(value==null||value.length===0){
return false;
}
return true;
},
isPhone:function(value){
var reg = /\\d+/;
if(reg.test(value)){
return true;
}
return false;
}
}
return function(value,type){
//type为检测类型,value为检测的值
if(!types[type]){
throw "检测类型不存在";
}
if(!types[type](value)){
return instructions[type];
}
return false;
}
})();
var Detect = function(){
this.result = [];
}
Detect.prototype.add = function(value,types){
if(!(types instanceof Array)){
throw "检测类型只能为数组";
}
for(var type of types){
var msg = validate(value,type);
if(!!msg){
this.result.push(msg);
}
}
}
Detect.prototype.getResult = function(){
var result = this.result;
return result.length?result:false;
}
var detect = new Detect();
detect.add("",["notEmpty"]);
//添加值的验证
detect.add(123,["isPhone"]);
//添加另外一个值的验证
console.log(detect.getResult());
//["不能为空"]