0

Given:

import { required, email, numeric } from 'validators'
let fields = ['name', 'email'];
validations: {
  name: {
     required
  },
  email: {
     required,
     email
  }
}

Now, I wanna do the require condition for each validation objects with a condition check.

Something like:

(fields.indexOf('name') > -1) ? 'required' : '';

How can I do this to dynamically set the validation conditions?

validations: {
  name: {
     (fields.indexOf('name') > -1) ? 'required' : '';
  },
  email: {
     (fields.indexOf('email') > -1) ? 'required' : '';,
     (fields.indexOf('email') > -1) ? 'email' : '';
  }
}

P.S: I know the above syntax is wrong. But wanted to achieve something like this.

user1012181
  • 8,648
  • 10
  • 64
  • 106
  • `{required: (fields.indexOf('name') > -1) ? required : false}` ? If you want to conditionally add the property, then you have to do this after the object is created: `if (fields.indexOf('name') > -1) { validations.name.required = required; }`. – Felix Kling Aug 31 '17 at 18:51
  • Possible duplicate of [In Javascript, how to conditionally add a member to an object?](https://stackoverflow.com/q/11704267/218196) – Felix Kling Aug 31 '17 at 18:57

0 Answers0