简体   繁体   中英

Simple Schema RegEx validation doesn't return error message

I'm doing some validation of my data with SimpleSchema. It seems to work for the most part except when trying to get the error message for regex validation.

What I have is:

FormSchema = new SimpleSchema({
  name: {
    label: "Name",
    type: String,
    min: 2,
    max: 25
  },
  email: {
    label: "Email",
    type: String,
    regEx: SimpleSchema.RegEx.Email
  }
});

var errors = [];

var data = {
  name: '',
  email: '',
};

var context = FormSchema.newContext();

if (!context.validate(data)) {
  var fields = context.invalidKeys();

  for (var i in fields) {
    errors.push(context.keyErrorMessage(fields[i].name));
  }
}

After this, errors contains the following:

["Name must be at least 2 characters", "Unknown validation error"]

From how I understand it, there is an default error message defined for the SimpleSchema.RegEx.Email regex.

How can I get the error message for the email field?

This question is now a few months old but i'll attempt an answer for anyone else that mail fall here...

I haven't run this code to test but my initial thoughts are that the first key 'name' is validated and if that fails it returns the error that you are seeing ["Name must be at least 2 characters", "Unknown validation error"] .

Let me explain further:

The place where you define: var data = { name: '', email: '', };

you have defined the name field's value as empty. You then perform a context.validate(data) some lines later. You have also configured a min: 2 option for the name which in the context of the type being a String then min option will validate whether the string in the data object contains a string with at least two characters long (not to mention the max stipulating an upper bounadry as well). In the context of the name parameter being set as a [String] then this means the name property of the schema is an array of stings which the min option will then attempt to validate against the number of entries in the name property.

Fix the error by providing in your data object a name that satisfies the string lengths or remove the min from the validation requirement.

You will then get an error from SimpleSchema complaining that the email property in the data object does not satisfy the Email regular expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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