Search code examples
regexangularangular2-formsangular4-formsangular-validation

No Space Validator in Angular


I'm hanlding more than 10 forms in my project with many input fields. The problem is my fields taking empty spaces as values. As for now what I did is getting the value of the field on change and trim it and check the length with 0. If yes throw 'don't use empty spaces' , else take the value.

<input (change)='check($event)'>

check(data){
   if(data.trim() === 0 ){
       console.log('contains empty spaces'   
   }else{
        console.log('contains data') 
   }
}

But as the field or form increases this will be a headache. So I'm trying to make this as common module. So that I'll use this as common like service.

note: the validation should happen on pretext (i.e) ' HelloWorld' should throw error but 'Hello World' should not. Can anyone give me some idea or suggestion to solve this issue..

Thanks in advance


Solution

  • trim.validator.ts

    export const trimValidator: ValidatorFn = (control: FormControl) => {
      if (control.value.startsWith(' ')) {
        return {
          'trimError': { value: 'control has leading whitespace' }
        };
      }
      if (control.value.endsWith(' ')) {
        return {
          'trimError': { value: 'control has trailing whitespace' }
        };
      }
      return null;
    };
    

    In any component that wants to use the trim.validator.ts

    import { trimValidator } from 'path/to/trim.validator'.ts
    
    ctrl: FormControl;
    
    ngOnInit() {
      this.ctrl = new FormControl('', trimValidator);
    )
    

    If you are using template driven forms, you need to create a validation directive. Just follow the steps from the official documentation

    Live demo