Home > Net >  Form validation using regex is not working TextField MUI React
Form validation using regex is not working TextField MUI React

Time:04-09

I am trying to add a regex pattern in inputProps for validation of Textfield and required but both not working, on click of next the empty or wrong input is also getting entered.

  <TextField
            id="outlined-basic"
            name="s_firstName"
            label="First Name"
            variant="outlined"
            defaultValue={user.s_firstName}
            onChange={handleChange} 
           
            inputProps={{pattern: "[a-z]"}
            required />

Please can you help what wrong is there validation not working?

CodePudding user response:

Your code seems fine, and required is working if you submit the form. It shows which field is required with a mark on the label.

In material ui,

required bool
If true, the label is displayed as required and the input element is required.

You will notice a warning popup as you type in your input.

For validation, you could write your own function with onChange.

  const handleValidation = (e) => {
    const reg = new RegExp("[a-z]");
    setValid(reg.test(e.target.value));
    setValue(e.target.value);
  };

With the error prop of <Textfield>, you could do something like this,

          <TextField
            id="outlined-basic"
            name="s_firstName"
            label="First Name"
            variant="outlined"
            value={value}
            onChange={(e) => handleValidation(e)}
            error={!valid}
            required={true}
          />

Check out this demo for code of two scenarios.

  • Related