Reputation: 10262
I have this very basic model with just one field name
that I want to validtate against a regex:
const Projects = new ProjectsCollection('projects');
Projects.schema = new SimpleSchema({
_id : {type: String, regEx: SimpleSchema.RegEx.Id},
name : {
type : String,
regEx: /^[a-zA-Z0-9]+((\s[a-zA-Z0-9]+)|(_[a-zA-Z0-9]+)|(-[a-zA-Z0-9]+)|(\.[a-zA-Z0-9]+))?$/
}
});
Projects.attachSchema(Projects.schema);
When the validation fails I get back a validation error saying that regex failed for Name
which is undesirable for me because it's ambiguous and the user has no idea what exactly I need him to enter.
I tried adding the following with no success:
Projects.schema.messages({
"regEx name": [{
msg: "test error message"
}]
});
This one however..works but the problem is that I could have any other model with a name field and it will spit out the same error message for all of them (and I plan on having another model with a name
field):
SimpleSchema.messages({
"regEx name": [{
msg: "test error message"
}]
});
I tried also with (no success):
SimpleSchema.messages({
"regEx projects.name": [{
msg: "test error message"
}]
});
I insert via methods and here's my insert code:
export const insert = new ValidatedMethod({
name : 'projects.insert',
mixins : [simpleSchemaMixin],
schema : Projects.simpleSchema().pick([
'name'
]),
schemaValidatorOptions: {
clean : true,
filter: false
},
run({name}) {
return Projects.insert({
name
}, null);
},
});
Any ideas on how am I supposed to configure my validation messages so that I can target them for specific fields?
Upvotes: 2
Views: 96
Reputation: 1512
This answer and question applies to v1 of meteor-simpl-schema
I had the same problem and this worked for me. I think that custom messages are instance based - are bound only to one simplSchema instance. Then in your validated-method, pick() will create a new SimplSchema instance, without your custom messages.
I needed to manually add a custom messages from the "parent" schema. In your case like this:
const insertProjectSchema = Projects.schema.pick('name');
insertProjectSchema.messages(Projects.schema._messages);
export const insert = new ValidatedMethod({
name : 'projects.insert',
mixins : [simpleSchemaMixin],
schema : insertProjectSchema,
schemaValidatorOptions: {
clean : true,
filter: false
},
run({name}) {
return Projects.insert({
name
}, null);
},
});
Upvotes: 0
Reputation: 20246
See the documentation for the special case of regex
messages:
In your case you should try:
Projects.schema.messages({
"regEx name": [
{
exp: /^[a-zA-Z0-9]+((\s[a-zA-Z0-9]+)|(_[a-zA-Z0-9]+)|(-[a-zA-Z0-9]+)|(\.[a-zA-Z0-9]+))?$/ ,
msg: "test error message"
}
]
});
Upvotes: 1