Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate object with schema?

This is the main file where I have schema and values. I have validation-type which returns true if type is string ect. Then there is validation file where I should validate values with schema.

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

validation-type

export function string(param) {
    return typeof param === "string"
  }

  export function number(param) {
    return typeof param === "number"
  }

  export function any(param) {
    return true;
  }

and this is validation.js

export function validate(schema, values) {
  let invalidValues = []


}

And I am stuck, don't know how to continue with validate function.

like image 795
Tomáš Hejlík Avatar asked May 08 '26 09:05

Tomáš Hejlík


1 Answers

What you're looking for is somewhat like following code block:

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;
}

You can refer this sandbox for better understanding.

Basically, the code is using the name of the validation function to give better validation error results. You can modify the error result pushed to invalidValues to get the type of error result you want.

like image 156
codedump Avatar answered May 10 '26 00:05

codedump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!