validator
validator是个好用的字符串校验工具,比如是否是数组,是否是邮箱,是否是bool值,很简单就可以搞定。
具体直接参考上面链接就可以了。很简单的。
var validator = require('validator');
function fetchData(userEmailStr, userAgeStr, isManStr) {
if (!validator.isEmail(userEmailStr)) {
return 'userEmail is error';
}
if (!validator.isNumeric(userAgeStr)) {
return 'userAgeStr is error';
}
if (!validator.isBoolean(isManStr)) {
return 'isManStr is error';
}
// do something
return 'allFormatPassed';
}
var res = fetchData('username@qq.com', '18', 'true');
console.log(res);// allFormatPassed
joi
joi是对象纲要描述语言以及JavaScript对象校验工具
还可以自定义约束条件
const Joi = require('joi');
const schema = Joi.object().keys({
userEmailStr:Joi.string().email(),
userAgeStr:Joi.number(),
isManStr:Joi.bool()
});
function fetchData(obj) {
// 这里定义变量时使用了对象的解构 变量名不能乱写
var {error,value} = Joi.validate(obj, schema);
if (error) {
return error.message;
}
// do something
return value;
}
var obj = { userEmailStr: '@qq.com', userAgeStr: 18, isManStr:'true' };
console.log(fetchData(obj));//child "userEmailStr" fails because ["userEmailStr" must be a valid email]