React js input onChange Validation is not Working

91 views Asked by At
onChange={(e) => {
    if (e.target.value.match("^[a-zA-Z]*$") != null) {
        setName(e.target.value);
        // console.log(setName);
    } else {
        toast.error("Please match the required format");
    }
}}

this required validation is not working. database is updated with empty string

2

There are 2 answers

1
Moshappp On
onChange = {(e) => {
  if(e.target.value.match("^[a-zA-Z]*$") === true){
    setName(e.target.value) 
  } else {
    toast.error("Please match the required format")
  }
}}
0
Ahmad Arif On

You can also use test like:

onChange={(e) => {
 if (/^[a-zA-Z]*$/.test(e.target.value)) {
     setName(e.target.value);
     // console.log(setName);
 } else {
     toast.error("Please match the required format");
 }
}}

Hope it maybe helpful.