Issue
So I want to validate that my input field to contain not just white space(spacebar) and special characters. I made a directive for white space here:
import { Directive } from '@angular/core';
import { NG_VALIDATORS, Validator, ValidationErrors, AbstractControl } from '@angular/forms';
@Directive({
selector: '[noWhiteSpace]',
providers: [{ provide: NG_VALIDATORS, useExisting: NoWhitespaceDirective, multi: true }]
})
export class NoWhitespaceDirective implements Validator {
constructor() { }
validate(control: AbstractControl): ValidationErrors {
if(!control.value || control.value.trim() == '')
{
return {'required' : true };
}
return null;
}
}
I'm still figuring out for the special characters. Hope to find some solution here.
Solution
These are the special characters in Regex.
., +, *, ?, ^, $, (, ), [, ], {, }, |, \
Reference: Regular Expression Tutorial (Regex Syntax Summary section)
Updated
While you can use the regex pattern below to validate the input with all its character(s) are special character:
^[^\w\s]+$
Match all characters other than [a-zA-Z0-9_] and whitespace from beginning to end.
In a directive way,
import { Directive } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
} from '@angular/forms';
@Directive({
selector: '[noSpecialCharactersOnly]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: NoSpecialCharacterOnlyDirective,
multi: true,
},
],
})
export class NoSpecialCharacterOnlyDirective {
constructor() {}
validate(control: AbstractControl): ValidationErrors {
if (/^[^\w\s]+$/.exec(control.value)) {
return { specialCharactersOnly: true };
}
return null;
}
}
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.