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

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

    What I did was created a validator that did the samething as angular for minLength except I added the trim()

    import { Injectable } from '@angular/core';
    import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';
    
    
    @Injectable()
    export class ValidatorHelper {
        ///This is the guts of Angulars minLength, added a trim for the validation
        static minLength(minLength: number): ValidatorFn {
            return (control: AbstractControl): { [key: string]: any } => {
                if (ValidatorHelper.isPresent(Validators.required(control))) {
                    return null;
                }
                 const v: string = control.value ? control.value : '';
                return v.trim().length < minLength ?
                    { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
                    null;
            };
        }
    
        static isPresent(obj: any): boolean {
            return obj !== undefined && obj !== null;
        }
    }
    

    I then in my app.component.ts overrode the minLength function provided by angular.

    import { Component, OnInit } from '@angular/core';    
    import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
    import { Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    export class AppComponent implements OnInit {  
      constructor() { }
    
      ngOnInit(): void {       
        Validators.minLength = ValidatorHelper.minLength;
      }
    }
    

    Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.

    Validators.compose([
          Validators.minLength(2)         
        ]);
    

提交回复
热议问题