Man*_*023 2 javascript validation
我正在寻找一种好的/优雅的方法来验证javascript对象是否具有必需的属性,到目前为止,这就是我所拥有的:
var fields = ['name','age','address'];
var info = {
name: "John Doe",
age: "",
phone: "123-456-7890"
}
var validateFields = function(o, required_fields) {
required_fields.forEach(function(field){
if(o.hasOwnProperty(field)){
if(o[field]){
console.log(field + ": " + o[field]);
}else{
console.log(field + " exists but is empty");
}
}else{
console.log(field + " doesn't exist in object");
}
});
}
validateFields(info, fields);
Run Code Online (Sandbox Code Playgroud)
在普通的javascript中,有没有更有效/更优雅的方法?
编辑:好的,所以我很高兴问我,因为我完全错过了一堆可能的条件,例如零。
随着优雅的出现,验证功能又如何呢?我还有其他情况要检查吗?
var fields = ['name','age','address'];
var info = {
name: "John Doe",
age: 0,
address: false,
phone: "123-456-7890"
}
var validateFields = function(o, required_fields, null_valid, zero_valid, empty_valid) {
var invalid_fields = [];
required_fields.forEach(function(field){
if(field in o){
switch(o[field]){
case '':
console.log(field + " exists but is empty");
if(!empty_valid){
invalid_fields.push(o[field]);
}
break;
case undefined:
console.log(field + " exists but is undefined");
invalid_fields.push(o[field]);
break;
case null:
console.log(field + " exists but is null");
if(!null_valid){
invalid_fields.push(o[field]);
}
break;
case 0:
console.log(field + " exists and the value is 0");
if(!zero_valid){
}
invalid_fields.push(o[field]);
break;
default:
console.log(field + ": " + o[field]);
break;
}
}else{
console.log(field + " doesn't exist in object");
invalid_fields.push(o[field]);
}
});
return invalid_fields;
}
var invalid = validateFields(info, fields, true, true, false);
console.log(invalid);
if(invalid.length >0){
console.log("ERROR: Missing fields");
}else{
console.log("Fields are valid");
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*dle 13
您可以使用https://github.com/jquense/yup来解决您的问题。
import * as yup from 'yup';
let schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
address: yup.string().required(),
});
var info = {
name: "John Doe",
age: "",
phone: "123-456-7890"
}
// check validity
schema
.isValid(info)
.then(function (valid) {
valid; // => false
});
Run Code Online (Sandbox Code Playgroud)
这不仅仅是检查字段是否存在,还确保数据类型正确,例如年龄是非负数。
如果您想要“优雅”,那么您所寻找的就是schema:
var schema = {
name: function (value) {
return /^([A-Z][a-z\-]* )+[A-Z][a-z\-]*( \w+\.?)?$/.test(value);
},
age: function (value) {
return !isNaN(value) && parseInt(value) == value && value >= 18;
},
phone: function (value) {
return /^(\+?\d{1,2}-)?\d{3}-\d{3}-\d{4}$/.test(value);
}
};
var info = {
name: "John Doe",
age: "",
phone: "123-456-7890"
};
function validate(object, schema) {
var errors = Object.keys(schema).map(function (property) {
var validator = schema[property];
return [property, validator(object[property])];
}).reduce(function (errors, pair) {
if (pair[1] === false) {
errors.push(new Error(pair[0] + " is invalid."));
}
return errors;
}, []);
if (errors.length > 0) {
errors.forEach(function (error) {
console.log(error.message);
});
} else {
console.log("info is valid");
}
}
validate(info, schema);Run Code Online (Sandbox Code Playgroud)
要解决@AndreFigueiredo的脚手架,您还可以检查,是否object包含该属性:
var schema = {
name: function (value) {
return /^([A-Z][a-z\-]* )+[A-Z][a-z\-]*( \w+\.?)?$/.test(value);
},
age: function (value) {
return !isNaN(value) && parseInt(value) == value && value >= 18;
},
phone: function (value) {
return /^(\+?\d{1,2}-)?\d{3}-\d{3}-\d{4}$/.test(value);
}
};
schema.name.required = true;
schema.age.required = true;
var info = {
// name: "John Doe",
age: "",
phone: "123-456-7890"
};
function validate(object, schema) {
var errors = Object.keys(schema).map(function (property) {
var validator = schema[property];
return [property, !validator.required || (property in object), validator(object[property])];
}).reduce(function (errors, entry) {
if (!entry[1]) {
errors.push(new Error(entry[0] + " is required."));
} else if (entry[1] && !entry[2]) {
errors.push(new Error(entry[0] + " is invalid."));
}
return errors;
}, []);
if (errors.length > 0) {
errors.forEach(function (error) {
console.log(error.message);
});
} else {
console.log("info is valid");
}
}
validate(info, schema);Run Code Online (Sandbox Code Playgroud)
这是一个现代化的解决方案,使用了ECMAScript 6版本的功能,包括解构,箭头功能Object.entries()、、模板文字和for...of:
const schema = {
name: value => /^([A-Z][a-z\-]* )+[A-Z][a-z\-]*( \w+\.?)?$/.test(value),
age: value => parseInt(value) === Number(value) && value >= 18,
phone: value => /^(\+?\d{1,2}-)?\d{3}-\d{3}-\d{4}$/.test(value)
};
let info = {
name: 'John Doe',
age: '',
phone: '123-456-7890'
};
const validate = (object, schema) => Object
.entries(schema)
.map(([property, validate]) => [
property,
validate(object[property])
])
.reduce((errors, [property, valid]) => {
if (!valid) {
errors.push(new Error(`${property} is invalid.`));
}
return errors;
}, []);
const errors = validate(info, schema);
if (errors.length > 0) {
for (const { message } of errors) {
console.log(message);
}
} else {
console.log('info is valid');
}Run Code Online (Sandbox Code Playgroud)
required以及validate分别执行和检查的版本:
const schema = {
name: value => /^([A-Z][a-z\-]* )+[A-Z][a-z\-]*( \w+\.?)?$/.test(value),
age: value => parseInt(value) === Number(value) && value >= 18,
phone: value => /^(\+?\d{1,2}-)?\d{3}-\d{3}-\d{4}$/.test(value)
};
schema.name.required = true;
schema.age.required = true;
let info = {
// name: 'John Doe',
age: '',
phone: '123-456-7890'
};
const validate = (object, schema) => Object
.entries(schema)
.map(([property, validate]) => [
property,
!validate.required || (property in object),
validate(object[property])
]).reduce((errors, [property, canValidate, isValid]) => {
if (!canValidate) {
errors.push(new Error(`${property} is required.`));
} else if (canValidate && !isValid) {
errors.push(new Error(`${property} is invalid.`));
}
return errors;
}, []);
const errors = validate(info, schema);
if (errors.length > 0) {
for (const { message } of errors) {
console.log(message);
}
} else {
console.log('info is valid');
}Run Code Online (Sandbox Code Playgroud)
我认为您应该更关心检查它的正确方法,而不是最优雅的方法。我将放置一个链接,指向托德·莫托(Todd Moto)关于此的非常好的帖子:请看一下
简而言之,您的代码应该如下所示:
var validateFields = function(o, required_fields) {
required_fields.forEach(function(field){
if(field in o){
if((typeof o[field] != 'undefined')){
console.log(field + ": " + o[field]);
}else{
console.log(field + " exists but is undefined");
}
}else{
console.log(field + " doesn't exist in object");
}
});
}
Run Code Online (Sandbox Code Playgroud)
注意:检查它是否有价值时要小心,JavaScript 中的许多表达式都是假值(例如 0、假等),但它们是有效值。
| 归档时间: |
|
| 查看次数: |
5818 次 |
| 最近记录: |