简体   繁体   English

如何在没有formik的情况下在react yup表单验证中显示错误消息

[英]How to show error messages in react yup form validations without formik

I am very new to YUP library.我对 YUP 图书馆很陌生。 I am trying to validate my form using yup.我正在尝试使用 yup 验证我的表单。

export const userLogin = yup.object({
    email:yup.string().email("Enter valid Email").required("This field is Required"),
    password:yup.string().min(5).max(12).required(),
}) 

   const data = {
     email:"example@gmail.com",
     password:"password"
   }



  userLogin.isValid(data)
   .then((response) =>{
      console.log(response) //true
  })

Now I am tying to get the error messages which I have mentioned in my schema.现在我要获取我在架构中提到的错误消息。 how can I get it?我怎么才能得到它?

You can use validate function of yup library instead of isValid function like:您可以使用yup库的validate function 代替isValid function ,例如:

userLogin
  .validate(data, { abortEarly: false })
  .then((responseData) => {
    console.log("no validation errors");
    console.log(responseData);
    setCurrentErrors([]);
})
  .catch((err) => {
    console.log(err);
    console.log(err.name); // ValidationError
    console.log(err.errors);
    setCurrentErrors(err.errors);
});

You can take a look at this sandbox for a live working example.您可以查看 此沙盒以获取实时工作示例。

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

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