Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Presense error triggered when it should give trigger format error #338

Open
silentrobi opened this issue Jul 1, 2020 · 1 comment
Open

Comments

@silentrobi
Copy link

silentrobi commented Jul 1, 2020

phone: {
    presence: { allowEmpty: false, message: 'is required.' },
    length: {
      maximum: 20
    },
    format: {
      pattern: "^[+]?[0-9][0-9]*$",
      flags: "i",
      message: "should be in +11111111111 or 1111111111 format."
    },
  }

When I type number in wrong pattern , the above code gives error array of size 2. Whereas, there should be one error. Normally, I take 1st index as error. In my code validate() is called dynamically using useEffect() which checks error each time useEffect hook runs

My useEffect() hook

useEffect(() => {
    const errors = validate(formState.values, schema);
    setFormState(formState => ({
      ...formState,
      isValid: errors ? false : true,
      errors: errors || {}
    }));
  }, [formState.values]);

This is the React jsx code where I used it

<TextField
                className={classes.numberTextField}
                error={hasError('phone')}
                fullWidth
                helperText={
                  hasError('phone') ? formState.errors.phone[0] : null
                }
                label="Phone"
                name="phone"
                onChange={handleChange}
                type="number"
                value={formState.values.phone || ''}
                variant="outlined"
              />
@yulolimum
Copy link

@silentrobi I saw your issue (although unrelated to mine) and since I'm working in a ReactJS project, I decided to reproduce your issue. TLDR, I couldn't:

image

The one differentiator between what you're doing and what I tried (since my setup is different), I validated outside of your hook. My suggestion would not to do an additional setFormState but to just define the errors and isValid on your component right above your return (that way they will recompute every time the component is rerendered).

Side note validate() returns an empty object when there are no errors. So, your ternary errors ? false : true will always be false because {} is truthy.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants