首页 > 解决方案 > 使用 Yup 验证不需要的表单字段?

问题描述

我想用 Yup 验证一个不需要的表单字段

const validationSchema = Yup.object().shape({
    firstname: Yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast ${min} alphabets`).max(20,`Should not exceed ${max} alphabets'),
    lastname: Yup.string().nullable().notRequired()
})

lastname: Yup.string.nullable().notRequired(). 我不知道如何继续进行,因为如果给出了输入,我有多个条件来验证该字段。

我的验证条件是:

  1. 应该只包含字母。
  2. 至少应包含 2 个字母,最多 20 个字母。

标签: javascriptyup

解决方案


match你应该使用你已经拥有的类似模式firstname。一种可能的方法是这样的:

const obj = {
    firstname: 'my name',
    lastname: 'asd'
  };
  const yupObj = yup.object().shape({
    firstname: yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast 3 alphabets').max(20,`Should not exceed 20 alphabets`),
    lastname: yup.string().nullable().notRequired().matches(/[a-zA-Z]{2,20}/, 'should have alphabets between 2 and 20')
  })
  yupObj
  .validate(obj)
  .then(function(value) {
    console.log(value); 
  })
  .catch(function(err) {
    console.log(err);
  });

推荐阅读