我正在尝试验证我们使用mui构建的react表单。我想使用mui文本字段错误属性来显示错误消息。提交时启动了验证,但没有显示错误消息。任何帮助都将不胜感激。谢谢
const history = useHistory();
const [errors, setErrors] = useState({});
const [open, setOpen] = useState(false);
const initialFormState = {
firstname: '',
lastname: '',
username: '',
contactnumber: '',
password: '',
confirmPass: '',
};
const [registration, setRegistration] = useState(initialFormState);
const validate = () => {
let temp = {...errors};
if ('firstname' in registration)
temp.firstname = registration.firstname ? '' : 'This field is required.';
if ('lastname' in registration)
temp.lastname = registration.lastname ? '' : 'This field is required.';
if ('username' in registration)
temp.username = /$^|.+@.+..+/.test(registration.username)
? ''
: 'Email is not valid.';
if ('contactnumber' in registration)
temp.contactnumberr =
registration.contactnumber.length > 6
? ''
: 'Minimum 6 numbers required.';
if ('password' in registration)
temp.password =
registration.password.length != 0 ? '' : 'This field is required.';
setErrors({
...temp,
});
if (registration) return Object.values(temp).every((x) => x == '');
};
const handleChange = (e) => {
setRegistration({
...registration,
[e.target.name]: e.target.value,
});
};
<TextField
variant="outlined"
margin="normal"
id="first name"
label="First Name"
style={{margin: 8}}
fullWidth
name="firstname"
value={registration.firstname}
onChange={handleChange}
className={classes.root}
error={errors.firstname}
/>
Material UI文本字段带有辅助文本属性:
helperText={errors.firstname}