简体   繁体   English

是的验证没有显示正确的消息

[英]Validation with Yup doesn't show the correct message

I'm using Yup and Formik to validate some fields.我使用和Formik验证某些字段。

One of the must be a number so this is how it was done:其中之一必须是数字,所以这是如何完成的:

import * as Yup from 'yup';

...

const requiredErrorMessage = 'This field is required';
const numberErrorMessage = 'This field is must be numerical';

 const validationSchema = Yup.object({
      anotherField: Yup.string().required(requiredErrorMessage),
      numberField: Yup.number(numberErrorMessage).required(requiredErrorMessage),
 });

So I would expect it to show the message "This field is must be numerical" if there are introduced different characters than numbers.因此,如果引入了与数字不同的字符,我希望它显示消息“此字段必须是数字”。

But it doesn't.但事实并非如此。 If I write "a" in the field the message is this: "price must be a number type, but the final value was: NaN (cast from the value "a" )."如果我在字段中写“a”,消息是这样的: “价格必须是number类型,但最终值是: NaN (从值"a" )。”

Why is it showing a different message?为什么它显示不同的消息?

对于数字类型的自定义消息,您应该调用 typeError() 函数:

numberField: Yup.number().typeError(numberErrorMessage).required(requiredErrorMessage),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM