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

前端 未结 18 1938
遇见更好的自我
遇见更好的自我 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:48

    To validate white space in starting in an input you can just call change event and do inline function for that.

    <input type="text" class="form-control"                     
                placeholder="First Name without white space in starting"
                name="firstName"
                #firstName="ngModel"
                [(ngModel)]="user.FirstName"
                (change) ="user.FirstName = user.FirstName.trim()"
                required/>

    0 讨论(0)
  • 2020-12-04 19:51

    You can create a custom validator to handle this.

    new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
    

    Add noWhitespaceValidator method to your component

    public noWhitespaceValidator(control: FormControl) {
        const isWhitespace = (control.value || '').trim().length === 0;
        const isValid = !isWhitespace;
        return isValid ? null : { 'whitespace': true };
    }
    

    and in the HTML

    <div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
    
    0 讨论(0)
  • 2020-12-04 19:53

    This is a slightly different answer to one below that worked for me:

    public static validate(control: FormControl): { whitespace: boolean } {
        const valueNoWhiteSpace = control.value.trim();
        const isValid = valueNoWhiteSpace === control.value;
        return isValid ? null : { whitespace: true };
    }

    0 讨论(0)
  • 2020-12-04 19:54

    To avoid the form submition, just use required attr in the input fields.

    <input type="text" required>

    Or, after submit

    When the form is submited, you can use str.trim() to remove white spaces form start and end of an string. I did a submit function to show you:

    submitFunction(formData){
    
        if(!formData.foo){
            // launch an alert to say the user the field cannot be empty
            return false;
        }
        else
        {
            formData.foo = formData.foo.trim(); // removes white 
            // do your logic here
            return true;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 19:56

    i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.

    Like here:-

    this.anyForm.valueChanges.subscribe(data => {
       for (var key in data) {
            if (data[key].trim() == "") {
              this.f[key].setValue("", { emitEvent: false });
            }
          }
        }
    

    Edited --

    if you work with any number/integer in you form control in that case trim function will not work directly use like :

    this.anyForm.valueChanges.subscribe(data => {
      for (var key in data) {
            if (data[key] && data[key].toString().trim() == "") {
              this.f[key].setValue("", { emitEvent: false });
            }
          }  
      }
    
    0 讨论(0)
  • 2020-12-04 19:58

    Prevent user to enter space in textbox in Angular 6

    <input type="text" (keydown.space)="$event.preventDefault();" required />
    
    0 讨论(0)
提交回复
热议问题