Skip to content

Custom Rules

Emerson Brito edited this page Mar 15, 2019 · 2 revisions

When creating custom rules keep in mind they must be designed to validate a single character at a time.

Custom rules can be based on:

  • Regular expression.
  • A function that test a character and returns a boolean value.

Regular Expression rules

For a RegEx rule Create a class that extends RegExpRuleBase.
Pass the rule specifier (a single character that will identify the rule) and the actual regular expression to the base class's constructor.

Example

In this example we will create a rule identified by the character ! (exclamation point). This rule should allow for only < (less than) and > (greater than) signs.

class GreaterLessThanRule extends RegExpRuleBase {
    constructor() {
        super('!', new RegExp(/^[<>]$/));
    }
}

Above code is all that is needed to create the rule. The next step is to register it with a directive.

In the component, create an array of custom rules:

let customRules: RuleBase[] = [ new GreaterLessThanRule() ];

In the template, pass the custom rules to the desired input.

<input inputMask mask="9!9" [rules]=customRules">

Function Based Rule

For a function based rule Create a class that extends RuleBase.
Pass the rule specifier (a single character that will identify the rule) to the base class's constructor and override the test() method.

Example

This is a function based implementation of the same rule from previous example:

class GreaterLessThanRule extends RuleBase{

    constructor() {
        super('!');
    }

    test(value: string): boolean {      
        return value && (value === '<' || value === '>');
    }
}
Clone this wiki locally