Form validation using regex is not working TextField MUI React - reactjs

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?

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.

If you want to show error message then use "helperText"
<TextField
error={value=== ""}
helperText={value=== "" ? 'Please enter a value!' : ' '}
>

Related

Unable to get Yup Validation to work in MUI with React Hook Form in a masked Controller field

I am on a dead end here with React Hook Form phone masking and validation. Any help will be greatly appreciated!
I am using React Hook Form and Yup for form and validation and MUI for UI. I was somehow able to add masking to my phone field using react-hook-form Controller component and react-input-mask for masking. But now I am not getting the Yup validation errors (helper text) that we get on form submit, on blur or on change.
I think it's because the masking already has hyphens which the field takes as value so it's technically never empty. But the problem is that when I add this field to the form, I don't get helper text to any of the other fields as well.
I have created a codesandbox for it. I want to make it a required field with minimum and maximum 15 characters (including + sign and two hyphens). I am not getting any helper text or error message and the form submits even if the user typed just one character.
Here's the Yup validation schema:
const Schema = Yup.object().shape({
cellPhone: Yup.string().min(15).max(15).required('Cell phone is required'),
});
const methods = useForm({
resolver: yupResolver(Schema),
defaultValues,
});
Here's the RHF form field:
<Controller
name="cellPhone"
control={control}
defaultValue=""
render={({ field: { onChange, value }, fieldState: { error } }) => (
<InputMask
mask="+99-999-9999999"
value={value}
onChange={onChange}
>
{(inputProps) => (
<TextField
error={!!error}
helperText={error?.message}
label="Cell phone"
variant="outlined"
type="text"
fullWidth
required
{...inputProps}
/>
)}
</InputMask>
)}
/>
Here's the codesandbox link:
https://codesandbox.io/s/magical-hooks-8zsgbb
If you have any solution, please let me know. Thanks!

How can I display different error messages on my MUI input field?

I have a form input field that displays an error if the user tries to submit while empty, but I also want to show a different error message is the input is not unique, I currently have this
<FormTextField
className={classes.nameInput}
errorMessages={[handleErrorMessage()]}
label="Recipe Name"
id="recipe-name"
isRequired
name="name"
onChange={handleChange}
placeholder="Recipe name"
validators={['required']}
value={slug}
autoFocus
/>
This is MUI v4
first solution:
you can use snackbar that found in material ui document:
https://v4.mui.com/components/snackbars/
and u can put one or more than one message
second solution:
maybe this post will help u, It is very close to your question:
https://stackoverflow.com/questions/49421792/how-to-use-material-uinext-textfield-error-props
you can put like this example:
<TextField
value={this.state.text}
onChange={event => this.setState({ text: event.target.value })}
error={text === ""}
helperText={text === "" ? 'Empty field!' : ' '}
/>

React-hook-form with Material-ui textfield without autoFocus defaultValue disappeared during form submit

I have problem using react-hook-form v7 + material-ui textfield. The defaultValue working if I set autoFocus or I manually change the textfield value. However if I just submit without mouse click on the filed that not autoFocus, the defaultValue disappeared during the form submit. Please check codesandbox link
Test 1: don't touch anything, click submit, you will see submit value only has title but missing name and desc
Test 2: mouse click or change value in name, you will see after submit the value of name is there
My question is how to make this default value always submit even though without mouse click or change the value of the textField?
Please help and thanks in advance
To use Material-ui with react-hook-form. It is better to wrap it with Controller to allow react-hook-form to link with the 3rd party library element.
https://react-hook-form.com/api/usecontroller/controller
Wrap Textfield with Controller
const { handleSubmit, control } = useForm();
...
<Controller
render={({ field }) => (
<TextField
autoFocus
margin="dense"
id="title"
label="Title"
type="text"
fullWidth
{...field}
/>
)}
control={control}
name="title"
defaultValue={data.title}
/>
...
After that, the default value will be able to work as expected.
Here is the codesandbox for demo.

Ant.design does not detect custom input component in Form.Item React

So, the main problem is, that antd form does not detect my custom input based on antd standard input:
There is a piece of form code (AddProduct):
<Form.Item
className="m-t-10"
name="price"
rules={[
{
required: true,
message: `${t('FORM.ERR.SHOP.PRICE')}`,
},
]}
>
<CurrencyInput size="small" placeholder={t('FORM.SHOP.PRICE_VAT')} name="price" />
</Form.Item>
There is my custom input (CurrencyInput):
return (
<Input size={props.size} placeholder={props.placeholder} name={props.name} type="number" prefix={settings[6].value} />
)
The problem is when I try to submit the form it does not detect currency input, throws err that this field is required. Any ideas are it possible to implement custom input, basically, it's more HOC than custom input
You need to pass to your custom component all props, because Form.Item pass to there onChange and value props
function CustomInput({size, placehodler, name, ...restProps}) {
return (
<Input size={size} placeholder={placeholder} name={name}
type="number" prefix={settings[6].value} {...restProps} />
)
}

material ui textfield cannot editable

I use material UI and a field text of type TextField. But when I was seized in my field email, the seizure does not appear to the screen and the value does not change in the email field.It always remains the same value.
Handle change is not working. the value is not passing to the handleChanges remains the same value
<TextField fullWidth={true}
className={classes.margin}
label={<FormattedMessage id="LoginTemplate.email" defaultMessage="Email" />}
id="email"
ref="email"
name="eamil"
type="email"
value={authentification.email}
onChange={this.handleChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Email className={classes.inputIconsColor} />
</InputAdornment>
),
}}
/>
Here is the code. Correct me What is the issue in that
Thanks in Advance.
In order to make the value change, you need to change a state (in the screen or external).
For instance (with bad performance but just to explain):
add to your cunstrunctor if exists:
constructor(props) {
super(props);
this.state = {
emailInputText: undefined //or empty string
}
}
Then change TextField component value and onChange props to:
value={this.state.emailInputText}
onChange={(text) => this.setState({emailInputText: text})}
I will consider to remove the ref='email'.

Resources