angulartypescriptangular-directiveangular-validation

Not allow an input field to contain only whitespace and special characters


So I want to validate that my input field contains not just whitespace (spacebar) and special characters. I made a directive for whitespace 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 the validation 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.

    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