0

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.

1
  • This is not going to answer the question directly, but I do believe it to be bad design to include phone number and email validation together. They have little cohesion and they are not likely to change for the same reason, hence they have different responsibilities. They should probably be separated. Commented Dec 4, 2020 at 15:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.