I am trying to validate the input fields using ngControl\'s value in angular 2. i need to validate that the user enters the value in upper case always.
Now we need
I would create a custom implementation of ControlValueAccessor. The latter would correspond to a directive that would listen the input event of the host. This way you will be able to put in uppercase what you user fills. The control will automatically contains the value in uppercase.
Here is the implementation:
@Directive ({
selector: 'input[uppercase]',
// When the user updates the input
host: { '(input)': 'onChange($event.target.value.toUpperCase())' }
})
export class UppercaseValueAccessor extends DefaultValueAccessor {
(...)
// When the code updates the value of the
// property bound to the input
writeValue(value:any):void {
if (value!=null) {
super.writeValue(value.toUpperCase());
}
}
}
Don't forget to register this custom value accessor in the directive providers. This way your custom value accessor will be used instead of the default one.
const UPPERCASE_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => UppercaseValueAccessor), multi: true});
@Directive ({
providers: [ UPPERCASE_VALUE_ACCESSOR ],
(...)
})
export class UppercaseValueAccessor ...
And add the directive in the directives attribute of the component where you want to use this approach.
See this class for more details:
This link could give additional hints (see section "NgModel-compatible component):