Este es el archivo principal donde tengo el esquema y los valores. Tengo un tipo de validación que devuelve verdadero si el tipo es una cadena, etc. Luego hay un archivo de validación donde debo validar valores con esquema.
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
tipo de validación
export function string(param) { return typeof param === "string" } export function number(param) { return typeof param === "number" } export function any(param) { return true; }
y esto es validación.js
export function validate(schema, values) { let invalidValues = [] }
Y estoy atascado, no sé cómo continuar con la función de validación.
Lo que estás buscando es algo así como el siguiente bloque de código:
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; }
Puede consultar este sandbox para una mejor comprensión.
Básicamente, el código usa el nombre de la función de validación para dar mejores resultados de error de validación. Puede modificar el resultado de error enviado a invalidValues
para obtener el tipo de resultado de error que desea.