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

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

    In hello.component.html

    <input [formControl]="name" />
    <div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>
    

    In hello.component.ts

    import { ValidatorFn, FormControl } from '@angular/forms';
    
    const trimValidator: ValidatorFn = (text: FormControl) => {
      if (text.value.startsWith(' ')) {
        return {
          'trimError': { value: 'text has leading whitespace' }
        };
      }
      if (text.value.endsWith(' ')) {
        return {
          'trimError': { value: 'text has trailing whitespace' }
        };
      }
      return null;
    };`
    
    export class AppComponent {
      control = new FormControl('', trimValidator);
    }
    

    Example Code

    0 讨论(0)
  • 2020-12-04 20:00

    I think a simple and clean solution is to use pattern validation.

    The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:

    /^(\s+\S+\s*)*(?!\s).*$/
    

    It can be set when adding the validators for the corresponding control of the form group:

    const form = this.formBuilder.group({
                name: ['', [
                    Validators.required,
                    Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
                ]]
            });
    
    0 讨论(0)
  • 2020-12-04 20:03

    To automatically remove all spaces from input field you need to create custom validator.

    removeSpaces(c: FormControl) {
      if (c && c.value) {
        let removedSpaces = c.value.split(' ').join('');
        c.value !== removedSpaces && c.setValue(removedSpaces);
      }
      return null;
    }
    

    It works with entered and pasted text.

    0 讨论(0)
  • 2020-12-04 20:04

    An alternative would be using the Angular pattern validator and matching on any non-whitespace character.

    const nonWhitespaceRegExp: RegExp = new RegExp("\\S");
    
    this.formGroup = this.fb.group({
      name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
    });
    
    0 讨论(0)
  • 2020-12-04 20:05

    Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

    In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:

    ...
    form: FormGroup;
    ...
    
    
    ngOnInit(){
        this.form.valueChanges
                .map((value) => {
                    // Here you can manipulate your value
                    value.firstName = value.firstName.trim();
                    return value;
                })
                .filter((value) => this.form.valid)
                .subscribe((value) => {
                   console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
                });
    
    }
    
    0 讨论(0)
  • 2020-12-04 20:05

    After lots of trial i found [a-zA-Z\\s]* for Alphanumeric with white space

    Example:

    New York

    New Delhi

    0 讨论(0)
提交回复
热议问题