[英]React/JavaScript - Validate two or more inputs
Is it possible to validate two or more inputs in the same file?是否可以验证同一文件中的两个或多个输入? As I am trying to create a second validator for another input.当我试图为另一个输入创建第二个验证器时。 I have one validator for a number input -我有一个用于数字输入的验证器 -
function FormVal() {
const [phone, setPhone] = React.useState<string>();
const [errors, setErrors] = React.useState<{ phone: string }>();
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
target: { value }
} = event;
setErrors({ phone: '' });
setPhone(value);
let reg = new RegExp(/^\d*$/).test(value);
if (!reg) {
setErrors({ phone: 'Only numbers' });
}
};
}
I would like to create second input like email or text but I don't want to create a new file and I was wondering how can I add another validator there.我想创建第二个输入,例如 email 或文本,但我不想创建新文件,我想知道如何在那里添加另一个验证器。
Instead of using the above-mentioned approach, What you can do is create a schema to validate the inputs.除了使用上述方法,您可以做的是创建一个模式来验证输入。 There are many great libraries for this.有很多很棒的图书馆。
In a large project writing a validator for each type of input can be a complex task.在大型项目中,为每种类型的输入编写验证器可能是一项复杂的任务。 You can use fastest-validator which is the fastest data validation library for javascript.您可以使用最快的验证器,它是 javascript 的最快数据验证库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.