Gerald Ylli
Gerald Ylli

Reputation: 116

React/JavaScript - Validate two or more inputs

Is it possible to validate two or more inputs in the same file ? As I am trying to create a second validator for another input. I have one validator for a number input -

function FormVal() {
  const [phone, setPhone] = React.useState<string>();
  const [errors, setErrors] = React.useState<{ phone: string }>();

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const {
      target: { value }
    } = event;
    setErrors({ phone: '' });
    setPhone(value);
    let reg = new RegExp(/^\d*$/).test(value);

    if (!reg) {
      setErrors({ phone: 'Only numbers' });
    }
  };
}

I would like to create second input like email or text but I don't want to create a new file and I was wondering how can I add another validator there.

Upvotes: 0

Views: 132

Answers (1)

frx
frx

Reputation: 215

Instead of using the above-mentioned approach, What you can do is create a schema to validate the inputs. There are many great libraries for this.

In a large project writing a validator for each type of input can be a complex task. You can use fastest-validator which is the fastest data validation library for javascript.

Upvotes: 1

Related Questions