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

229
Visualizações
Javascript | Validate structure of object based on custom schema

Working on a API that needs to validate the strucutre of the incoming request object. Based on other answers to similar questions, I have tried to create a solution that doesn't seem to be working.

My code so far:

 const testObj = {
            "uuid": {
                "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
                "type": "id"
            },
            "rate": {
                "value": 0.12,
                "type": "percent"
            }
        }

        let ok = true;

        ok = testObj === OBJECT_SCHEMA; // is false. Expected to be true

My validation schema:

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}

Can aynone pinpoint what I'm doing wrong here?

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

0

testObj === OBJECT_SCHEMA is returning false because the value of testObj and OBJECT_SCHEMA types are equal but not values.

My recommendation would be to checkout Yup or Zod for creating a validation

about 4 years ago · Juan Pablo Isaza Relatório

0

Something to get you started:

let validate = (obj, schema) =>
    typeof obj === 'object'
        ? Object.keys(schema).every(k => validate(obj[k], schema[k]))
        : obj?.constructor === schema;

//

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}


testObj = {
    "uuid": {
        "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
        "type": "id"
    },
    "rate": {
        "value": 0.12,
        "type": "percent"
    }
}

console.log(validate(testObj, OBJECT_SCHEMA))
testObj.rate.value = 'foo'
console.log(validate(testObj, OBJECT_SCHEMA))
delete testObj.rate.value
console.log(validate(testObj, OBJECT_SCHEMA))

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