Minide
Minide

Reputation: 305

Multiple conditionals in one line for Javascript

I am learning React and Javascript. So far it's quite easy but when it comes to resolve how to validate multiple values for an input and print and error I cannot resolve it with conditional operators.

I have this react-hook-form component with 3 validation requirements: required, minLength and pattern:

<Input
  {...register('password', {
    required: true,
    minLength: minChars,
    pattern: passwordValidation,
    })}
    type='password'
    label={t('common:forms.password')}
    placeholder={t('common:forms.min_char', {
      count: minChars,
    })}
    errors={
           errors.password
             && errors.password.type === 'minLength'
             ? errors.password.type === 'required'
             ? errors.password.type === 'minChars'
                    ? true
                    : true
                  : ''
              }
            />

I want to print the true value if any or all 3 validations are active. I tried something like:

{errors.password ? true : ''}

And doesn't work

Also this one fails

{errors.password && errors.password.type === 'minLength' &&  errors.password.type === 'required' && errors.password.type === 'minChars' ? true : ''}

Maybe i cannot resolve this with conditional operators and i need to abstract this validation elsewhere or use yup.

Upvotes: 0

Views: 295

Answers (1)

Tom
Tom

Reputation: 5667

I want to print the true value if any or all 3 validations are active.

Then you should use the logical OR operator || instead of AND && :

{errors.password && (errors.password.type === 'minLength' || errors.password.type === 'required' || errors.password.type === 'minChars') ? true : ''}

Upvotes: 1

Related Questions