Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

353
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!