0

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?

2
  • stackoverflow.com/questions/55258192/… That can help you Commented Apr 9, 2022 at 0:16
  • @mchowdam; Thanks I tried but it didnt worked . I want to display message also about wrong entry. Any sample code if you can provide, MUI v5 Commented Apr 9, 2022 at 0:40

2 Answers 2

2

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.

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

6 Comments

Thanks for responsing, what I have done how to display the error message and if user enters thewrong format and pressess next button its not working. @AnthonyDev220
for the one which I have asked there are many fields of form, then can be checked but how to show error message thant is coming on hover now.
@Tanyamaheshwari could you rephrase your question? I don't quite get what you are asking.
I want to display error message also with the error. Secondly if user enters wrong value and presses submit button, the user moves ahead @AnthonyDev220:
@Tanyamaheshwari I think you might need to post a new question with detailed example, and provide your code and what you have tried, to prevent excessive discussion here.
|
-1

If you want to show error message then use "helperText"

<TextField
    error={value=== ""}
    helperText={value=== "" ? 'Please enter a value!' : ' '}
>

Comments

Your Answer

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