How to validate white spaces/empty spaces? [Angular 2]

前端 未结 18 2086
遇见更好的自我
遇见更好的自我 2020-12-04 19:14

I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?

18条回答
  •  伪装坚强ぢ
    2020-12-04 19:42

    I had a requirement where in the Firstname and Lastname are user inputs which were required fields and user should not be able to hit space as the first character.

    Import AbstractControl from node_modules.

    import { AbstractControl } from '@angular/forms';
    

    check if the first character is space If yes then blank the value and return required: true. If no return null

    export function spaceValidator(control: AbstractControl) {
    if (control && control.value && !control.value.replace(/\s/g, '').length) {
        control.setValue('');
        console.log(control.value);
        return { required: true }
    }
    else {
        return null;
    }
    }
    

    the above code will trigger an error if the first character is space and will not allow space to be the first character.

    And in form builder group declare

    this.paInfoForm = this.formBuilder.group({
            paFirstName: ['', [Validators.required, spaceValidator]],
            paLastName: ['', [Validators.required, spaceValidator]]
    })
    

提交回复
热议问题