Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom ValidationRule

Tags:

aurelia

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

like image 489
jbailie1991 Avatar asked Nov 28 '25 14:11

jbailie1991


1 Answers

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);
like image 126
Mikhail Shilkov Avatar answered Dec 01 '25 13:12

Mikhail Shilkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!