There is some restrictions in name field so I am trying to validate name field using directive as below. Inside directive I am using regular expression to check valid name and then replacing valid name into textbox using valueAccessor.writeValue(newVal)
Here issue is when I am trying to type middle of some word in textbox cursor jump at the end.
@Directive({
selector: '[validateName]',
host: {
'(ngModelChange)': 'onInputChange($event, false)',
'(keydown.backspace)': 'onInputChange($event.target.value, true)',
'(focusout)': 'removeClass()'
}
})
export class NameValidator {
constructor(public model: NgControl,public renderer: Renderer, public el: ElementRef) { }
onInputChange(event, backspace) {
if (!backspace) {
// Remove invalid characters (keep only valid characters)
var newVal = event.replace(/^[0-9\s]/g, '').replace(/[^A-Za-z0-9_$]/g,'');
// Add class for invalid name.
if (/^[0-9\s]/g.test(event) || /[^A-Za-z0-9_$]/g.test(event)) {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', true);
}
else {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
}
}
removeClass() {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
}
}