这是我拥有模式和值的主文件。我有一个验证类型,如果类型是字符串等,则返回true。然后是验证文件,我应该在其中使用模式验证值。
import * as ValidationTypes from './lib/validation-types'
import {validate} from "./lib/validation";
const schema = {
name: ValidationTypes.string,
age: ValidationTypes.number,
extra: ValidationTypes.any,
};
const values = {
name: "John",
age: "",
extra: false,
};
let result = validate(schema, values); //return array of invalid keys
console.log(result.length === 0 ? "valid" : "invalid keys: " + result.join(", "));
//invalid keys: age
验证类型
export function string(param) {
return typeof param === "string"
}
export function number(param) {
return typeof param === "number"
}
export function any(param) {
return true;
}
这就是validation.js
export function validate(schema, values) {
let invalidValues = []
}
我被卡住了,不知道如何继续验证函数。
您要查找的有点像以下代码块:
export function validate(schema, values) {
let invalidValues = [];
// Make sure schema is an object
if (typeof schema !== "object") {
throw new Error("Schema must be an object");
}
// Loop over each key of the schema
Object.keys(schema).forEach((schemaKey) => {
// Get the validation function associated with
// the specific key of the validation schema
const validationFn = schema[schemaKey];
// Sanity check. Check if the variable associated
// with the schemaKey is a function or not.
if (typeof validationFn !== "function") {
throw new Error("Invalid validation function");
}
// Get the validation result of the schemaKey
// through it's validation function.
// The schema key is also used in the values passed
// to this function.
const validationResult = validationFn(values[schemaKey]);
// Check if the validation is true
if (!validationResult) {
// If the validation is not true
// Push the error message
invalidValues.push(
// `schemaKey` is the name of the variable
// `validationFn.name` gives the name of the validation function
// which in this case is associated with variable type
`[${schemaKey}] must be of type [${validationFn.name}]`
);
}
});
return invalidValues;
}
你可以参考这个沙箱来更好地理解。
基本上,代码使用验证函数的名称来给出更好的验证错误结果。您可以修改推送到invalidValues
的错误结果,以获得您想要的错误结果类型。