Home > Software engineering >  Not allow an Input Field to Contain Only White Space and Special Characters
Not allow an Input Field to Contain Only White Space and Special Characters

Time:09-11

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.

CodePudding user response:

You can use validators.pattern('regex') in formcontrol itself so that it will work fine.

Here regex is for validation special characters

CodePudding user response:

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.

Demo @ Regex 101


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;
  }
}

Demo @ StackBlitz

  • Related