validate-js |如何验证空白字段?

时间:2019-02-01 05:10:34

标签: javascript react-native

我在我的本机代码上使用validate.js https://github.com/ansman/validate.js/来验证字段,它对于必填字段工作正常,但对可选字段无效。 例如我有一个电子邮件输入字段,但是它是可选的,如果用户输入电子邮件,则应该验证电子邮件。

在Github上,它说使用allowEmpty: true,但不起作用。

以下是我正在使用的代码:

Constaraints.js

email: {
     presence: {
         allowEmpty:true
     },
     email: {
       message: '^Please enter a valid email address',
     }
   }

验证者代码:

export default  function validator (field, value)  {
  // Creates an object based on the field name and field value
  // e.g. let object = {email: 'email@example.com'}
  let object = {}
  object[field] = value

  let constraint = constraints[field]
  // console.log(object, constraint)

  // Validate against the constraint and hold the error messages
  const result = validate(object, { [field]: constraint })
  // console.log(object, constraint, result)

  // If there is an error message, return it!
  if (result) {
    // Return only the field error message if there are multiple
    return result[field][0]
  }

  return null
}

0 个答案:

没有答案
相关问题