Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda