Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

354
Vistas
Apply dynamic validations on JS object

I am tying to apply custom validations on each item of JS object according to name of the item. for ex, age_int should be of type int else it should throw error and If try to edit with wrong datatype, it should throw error.

const obj { age_int: 2, name string: "adam", job: null, } 

const validatingobject = typecheck(obj)

validatingobject.age_int = 2.25 // throws error 

validatingobject.age_int = 2 

validatingobject.job = "fireman"
 
validatingobject.address_string = 20 // throws error
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Its not the complete code, you should complete as your needs:

   function typecheck(obj){
       for (let key in obj) {
          if (key.includes("int") && Number.isInteger(obj[key])){
             console.log(key, obj[key], "is int");
          }
          // you need to complete by your needs
       }
   }

enter image description here

Another option:

const typecheck = Object.freeze(
  // Create new objecct with NO prototype: null 
  Object.create(null, {
    // 'a_int' set/get
    a_int: {
      get() {
        // Check: Symbol existence
        return this[Symbol.for('a_int')] 
      },
      set(val) {
        if(!Number.isInteger(val))
           throw new DOMException("not int")
        this[Symbol.for('a_int')] = val;
      }
    }
  })
);

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda