Asked By: Anonymous
The intro for the aurelia-validation plugin contains a section on creating custom ValidationRules, by extending the ValidationRule class and passing it to the passes function. The example given is as follows:
import {ValidationRule} from './plugins/validation/';
export class MyValidationRule extends ValidationRule{
constructor (isValid) {
super(
isValid, //pass any object as 'threshold'
(newValue, threshold) => { //pass a validation function
return threshold;
}
(newValue, threshold) => { //Optionally pass a function that will provide an error message
return `needs to be at least ${threshold} characters long`;
},
);
}
}
What do I do with this? For example, for demo purposes if i wanted to make a function that checks if the value is a phone number with regex, how would i code that using this template? I’m asking because the documentation is sparse with examples; there are none for writing custom validation rules and the other example shows how to add one to the ValidationGroup prototype but I would like to know both methods of adding a custom rule
Solution
Answered By: Anonymous
First, you don’t have to create a custom validation rule class. You may just make a function which accepts an argument and returns the validation result, e.g.
function validatePhoneNumber(newValue) {
return true/*your RegExp check should return true/false here*/;
}
and then
this.validation = validation.on(this)
.passes(validatePhoneNumber);
If you think you need a class to make validation more generic, try something like
import {ValidationRule} from './plugins/validation/';
export class RegExpValidationRule extends ValidationRule {
constructor (regExp, errorMessage) {
super(
regExp,
(newValue, threshold) => {
return true/*your RegExp check should return true/false here*/;
},
(newValue, threshold) => {
return errorMessage;
}
);
}
}
and then
var validationRule = new RegExpValidationRule(/*your RegExp*/, 'Invalid phone number');
this.validation = validation.on(this)
.passesRule(validationRule);