0

So, let's say that i have an object:

const object = {
   name: 'Lukas'
}

Now i wish to validate this object, so i'm doing this:

const validator = {
  name: value => {
    if (!value) return 'No value provided'
  }
}

How to pass object to validator to correctly check value?

validator['name'] returns function validator[object] returns undefined

What i'm doing wrong?

Lukas
  • 7,384
  • 20
  • 72
  • 127

2 Answers2

1

You can call it with validator.name(), if you don't know the name of the property you can iterate through the object properties an call on each of them.

    const object = {
           name: 'Lukas',
           lastname: 'Smith'
    }

    const validator = {
      name: value => {
        if (!value) return 'No value provided'
        else return value;
      },
      lastname: value => {
        if (!value) return 'No value provided'
        else return value;
      }
    }



        for(let key in validator)
        {
          if (validator.hasOwnProperty(key) && 
              object.hasOwnProperty(key))
          {
            console.log(validator[key](object[key]))    
          }
        }

Correct me If I didn't understood but if you want to validate but if you want to validate calling from your validator you could do it like this..

Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
  • Ok, looks nice, but what if i want to validate each key/value in object separately, like: `name: value => {` / `lastname: value => {`? – Lukas Mar 06 '18 at 12:50
  • Just one more, how to check that there is no provided value of existing validator? – Lukas Mar 06 '18 at 13:01
  • 1
    Its already beeing checked with this validation object.hasOwnProperty(key) – Renzo Calla Mar 06 '18 at 13:04
  • Thanks guys you help me a lot! – Lukas Mar 06 '18 at 13:33
  • You really should drop those `hasOwnProperty` checks - the `validator` one [because it's useless](https://stackoverflow.com/a/45014721/1048572) and the `object` one because the validator should still check it when it's `undefined`. – Bergi Mar 06 '18 at 13:34
  • Actually did this because of that what you've just mentioned. – Lukas Mar 06 '18 at 14:13
1

You can use like this validator['name'](false) . Because your name property type is a function.

const validator = {
  name: value => {
    if (!value) return 'No value provided'
    else return "else"
  }
}

console.log(validator['name'](false));
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37