Reactjs 是的:测试失败的验证

Reactjs 是的:测试失败的验证,reactjs,formik,yup,Reactjs,Formik,Yup,我正在使用yup验证我的react表单 我的问题是: 我有下面的模式来验证输入字段 object().shape({ firstname: string() .required('First Name is required') .test('length', 'First Name must have more than 1 character', (value) => { console.log(value &&a

我正在使用yup验证我的react表单

我的问题是:

我有下面的模式来验证输入字段

object().shape({
    firstname: string()
        .required('First Name is required')
        .test('length', 'First Name must have more than 1 character', (value) => {
            console.log(value && value.length < 2 ? true : false);
            return value && value.length < 2 ? true : false;
        })
        .test('alphabets', 'Name must only contain alphabets', (value) => {
            console.log(!/^[A-Za-z]+$/.test(value));
            return !/^[A-Za-z]+$/.test(value);
        })
});
object().shape({
名字:string()
.required('需要名字')
.test('length','First Name必须有超过1个字符',(value)=>{
console.log(value&&value.length<2?true:false);
返回值&&value.length<2?真:假;
})
.test('字母','名称必须仅包含字母',(值)=>{
console.log(!/^[A-Za-z]+$/.test(value));
返回!/^[A-Za-z]+$/.test(值);
})
});
当我输入单个字符时,它会显示
名称必须仅包含字母
错误消息,当我尝试键入更多字符时,它会显示
名字必须包含多个字符
错误消息

我应该做错什么


任何人,请帮我解决这个问题?

您的验证方式似乎都不对,如果验证通过,您希望返回
true
,如果验证失败,则返回
false


在第一次验证中
value&&value.length<2?true:false
您正在查找
value.length>2
而不是
您似乎在以错误的方式执行验证,如果验证通过,您希望返回
true
,如果验证失败,则返回
false

在第一次验证中
value&&value.length<2?true:false
您正在查找的是
value.length>2
而不是

object().shape({
    firstname: string()
        .required('First Name is required')
        .test('length', 'First Name must have more than 1 character', (value) => {
            return value && value.length > 2;
        })
        .test('alphabets', 'Name must only contain alphabets', (value) => {
            return /^[A-Za-z]+$/.test(value);
        })
});