同时显示在输入中显示错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了同时显示在输入中显示错误相关的知识,希望对你有一定的参考价值。
我一直在使用Yup和Formik在React中进行表单验证。现在,当用户模糊输入时,将显示错误。这是我的代码:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
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> /> ); }
如何在用户输入内容的同时显示错误?
我一直在使用Yup和Formik在React中进行表单验证。现在,当用户模糊输入时,将显示错误。这是我的代码:...
假设它应该为0 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');
});
}
以上是关于同时显示在输入中显示错误的主要内容,如果未能解决你的问题,请参考以下文章
Angularjs - 如何获得 ng-message required 错误以同时显示和禁用输入按钮
Android:RecyclerView 不显示片段中的列表项