如何从错误消息中删除约束字段

时间:2019-04-30 04:26:47

标签: react-native validate.js

我正在使用validate.js在我的本机应用程序上进行表单验证。一切正常,就像我从这些帖子中看到的一样:https://medium.com/@pavsidhu/validating-forms-in-react-native-7adc625c49cfError using validate.js on React Native - Unknown validator minimum

代码可以正常工作并给出正确的错误消息,但有1个问题:它以错误消息为字符串给出约束字段名称。

Profile picture Please upload image!

在字符串中产生了约束字段(“个人资料图片”)和错误消息(“请上传图片!”)的错误。

我的代码:

import validate from 'validate.js';

// Constrain example
const constraints = {
emailAddress: {
    presence: {
        message: "Cannot be blank."
    },
    format: {
        pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        message: 'Invalid email id',
    },
    email: true
},
password: {
    presence: {
        message: "Cannot be blank."
    },
    length: {
        minimum: 6,
        message: 'Your password must be at least 6 characters'
    }
},
profilePicture: {
    presence: {
        message: "Please upload image!"
    }
},
}

// Function
const formValidator = (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]

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

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

return null
}

在表单页面上的用法:

let errorprofilePicture = Validator("profilePicture", profilePicture);

this.setState({
  errorProfilePicture: errorprofilePicture
}

我如何使其仅吐出错误消息? 类似于Please upload image!

谢谢!

0 个答案:

没有答案