[英]Displaying errors simultaneously writing in an input
我一直在使用 Yup 和 Formik 在 React 中進行表單驗證。 現在,當用戶模糊輸入時,會顯示錯誤。 這是我的代碼:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
import React from "react";
import { Formik, Field } from "formik";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import * as yup from "yup";
const FirstNameInputComponent = ({ field, ...props }) => {
const { errorMessage, touched } = props;
const { name, value, onChange, onBlur } = field;
return (
<TextField
value={value}
name={name}
error={touched && errorMessage ? true : false}
label="نام"
helperText={touched && errorMessage ? errorMessage : undefined}
onChange={onChange}
onBlur={onBlur}
/>
);
};
const App = () => {
const validationSchema = yup.object().shape({
first_name: yup.string().required()
});
return (
<Formik
initialValues={{
file: undefined,
text: undefined
}}
validationSchema={validationSchema}
validateOnBlur={true}
render={({
values,
errors,
touched,
handleChange,
handleBlur,
setFieldValue
}) => {
return (
<form>
<Field
name="first_name"
component={FirstNameInputComponent}
errorMessage={errors["first_name"]}
touched={touched["first_name"]}
onChange={handleChange}
onBlur={handleBlur}
/>
</form>
/>
);
}
如何在用戶寫入輸入的同時顯示錯誤?
假設它應該是 0 < foo < 10。
const [foo, setFoo] = useState(1);
const [errMsg, setErrMsg] = useState('');
// declare schema with Yup
const schema = Yup.object().shape({
num: Yup.number()
.min(1, 'min')
.max(9, 'max'),
});
// in input change handler
const onInputChange = val => {
schema
.validate({
num: val,
})
.then(() => {
setFoo(val);
setErrMsg('');
})
.catch(() => {
setFoo(val); // comment this out if you don't want to set the value when there's an error
setErrMsg('Number must be between 1 and 10');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.