-
Notifications
You must be signed in to change notification settings - Fork 1
Custom Rules
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.
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.
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">
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.
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 === '>');
}
}