Angular 2 form Validation
scenario:
If user try to enter the special character in to the input type="text", it should be prevented from being entered ?
special characters should not appear in to the corresponding text box ?
Angular 2 form Validation
scenario:
If user try to enter the special character in to the input type="text", it should be prevented from being entered ?
special characters should not appear in to the corresponding text box ?
code, which shown below fix the caret position problem
1. changing the event type to '(input)' inside the host listener.
2. inside the class define the start and end position of the caret, it solves the problem
@Directive({
selector: '[ngModel][maskSpecialCharacter]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(input)': 'onInputChange($event.target.value, true)'
}
})
export class SpecialCharacterMask {
constructor(public model: NgControl, public ele: ElementRef, public render: Renderer) { }
onInputChange(event, backspace) {
var position = this.ele.nativeElement.selectionStart;
var value = event.replace(/[!$%^&*()+|~=`{}\[\]:";#@'<>?,.\/\\]/gi, '');
this.render.setElementProperty(this.ele.nativeElement, "value", value);
this.ele.nativeElement.selectionEnd = position;
}
}
You can create a custom validator,
import { FormControl } from '@angular/forms'
export function restrictedWords(words) {
return (control: FormControl): { [key: string]: any } => {
if (!words) return null
var invalidWords = words.map(w => control.value.includes(w) ? w : null)
.filter(w => w != null)
return invalidWords && invalidWords.length > 0
? { 'restrictedWords': invalidWords.join(', ') }
: null
}
}
Call the custom validator function from your form,
this.textBox1 = new FormControl('',[Validators.required, Validators.maxLength(400), restrictedWords(['foo','bar'])])
Approach for Angular Reactive Form:
Need to add a Validator in form Validation. Also, below regex will not work with internationalization. Please change the regex as per need.
this.form= this.formBuilder.group({
name: ['', [ Validators.required, Validators.pattern(/^[a-zA-Z0-9!@#$%^&*()]+$/)] ],
description: ['']
});
Please note you don't need quotes for Validators.pattern method
Approach 2
export function isSecuredInput(input: string): boolean {
const tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
const tagOrComment = new RegExp(
'<(?:'
// Comment body.
+ '!--(?:(?:-*[^->])*--+|-?)'
// Special "raw text" elements whose content should be elided.
+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
+ '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
// Regular name
+ '|/?[a-z]'
+ tagBody
+ ')>',
'gi');
return input.search(tagOrComment) === -1 ? true : false;
}
Changes in Form:
isValidInput(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!isNullOrUndefined(control.value)) {
return isSecuredInput(control.value.toString()) ? null : { invalid: true};
}
return null;
};
}
and Form would be
this.form = this.formBuilder.group({
name: new FormControl('', {
validators: [Validators.required, this.isValidInput()],
updateOn: 'change'
})
})
Source isSecure is from Sanitize/Rewrite HTML on the Client Side
Try Using Pattern as
this.form= this.fb.group({
name: ['', [Validators.pattern('[a-zA-Z0-9 ]')]],
});