【问题标题】:How to validate white spaces/empty spaces? [Angular 2]如何验证空格/空格? [角度 2]
【发布时间】:2017-01-07 07:11:07
【问题描述】:

我想在我的 angular 2 表单中避免空格/空格? 可能吗? 如何做到这一点?

【问题讨论】:

标签: angular validation typescript input


【解决方案1】:

为避免表单提交,只需在输入字段中使用required attr。

<input type="text" required>

或者,提交后

提交表单后,您可以使用 str.trim() 删除字符串开头和结尾的空格。我做了一个提交功能给你看:

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;
    }

}

【讨论】:

  • 感谢您的帮助,但我需要的是避免用户只添加空格并保存表单。我相信有可能以某种方式验证它。你怎么看?
  • 我还没有使用 angular 2 形式的输入掩码。如果我这样做,我会帮助你。但现在我不能。尝试搜索 angular 2 的掩码输入;)
  • 谢谢!我会设法找到它。
【解决方案2】:

也许这篇文章可以帮到你http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

在这种方法中,您必须使用 FormControl 然后观察值的变化,然后将掩码应用于该值。一个例子应该是:

...
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));
            });

}

【讨论】:

    【解决方案3】:

    您可以创建自定义验证器来处理此问题。

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

    向你的组件添加 noWhitespaceValidator 方法

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

    在 HTML 中

    <div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
    

    【讨论】:

    • 我认为我更喜欢这种方法,因为它使规则可重用。甚至被我的回应标记为正确的。
    • 为了使其在其他组件中可重用:将“public”替换为“export function”,然后将其放入文件中(例如:src/app/utils/no-whitespace.validator.rs),并添加行以导入 FormControl。现在您可以将此验证器导入到您喜欢的任何控件中:)
    • @rmcshary 你说得对。这就是我们需要编写和维护代码的方式。
    • 如何修改noWhitespaceValidator 以允许在tsconfig.json 中设置strictNullChecks: true
    • //以上答案是完美的,仅建议进行一项检查以避免与角度所需的验证器发生冲突。 public noWhitespaceValidator(control: FormControl) { const isWhitespace = control.value.length > 0 && (control.value).trim().length === 0;常量 isValid = !isWhitespace;返回是有效的?空:{'空白':真}; }
    【解决方案4】:

    我所做的是创建了一个验证器,它对 minLength 执行与 angular 相同的操作,除了我添加了 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;
        }
    }
    

    然后我在我的 app.component.ts 中覆盖了 angular 提供的 minLength 函数。

    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;
      }
    }
    

    现在在任何使用 angular 内置验证器的 minLength 的地方,它都会使用您在帮助程序中创建的 minLength。

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

    【讨论】:

      【解决方案5】:

      如果您使用 Angular Reactive Forms,您可以创建一个带有函数的文件 - 验证器。这将不允许只输入空格。

      import { AbstractControl } from '@angular/forms';
      export function removeSpaces(control: AbstractControl) {
        if (control && control.value && !control.value.replace(/\s/g, '').length) {
          control.setValue('');
        }
        return null;
      }
      

      然后在你的组件打字稿文件中使用像这样的验证器。

      this.formGroup = this.fb.group({
        name: [null, [Validators.required, removeSpaces]]
      });
      

      【讨论】:

      • 我知道这个答案已经有一年多了,但我只是试了一下。当我创建我的表单控件时,我将它默认为 '' 而不是 null,这导致了一个无限循环。我将默认值更改为 null 并继续测试。如果我进入该字段,输入几个字符然后删除它们,它表示该字段是有效的,即使它应该没有通过所需的验证。这是一个耻辱。我真的很喜欢这个解决方案。
      • 我在我的代码中尝试了这种方法,但它没有抛出所需的错误,即使控件具有空值作为 ''。所以在 control.setvalue('') 下的函数 {required : true} 中返回;它就像一个魅力。谢谢。
      【解决方案6】:

      防止用户在 Angular 6 的文本框中输入空格

      <input type="text" (keydown.space)="$event.preventDefault();" required />
      

      【讨论】:

      • 您仍然可以粘贴空格,或使用 Alt+0160。
      • 对于注意到粘贴仍然有效的其他人,您可以使用自定义指令来禁用粘贴。见stackoverflow.com/questions/47384952/…
      • @Nicky 你可以,但是如果用户想要粘贴一些东西(合法)怎么办?禁用粘贴会降低可用性。
      • @DanielShatz 您可以为此调用更改事件内联函数。像输入元素中的 (change)="yourvalue = yourvalue.trim()"。
      • 问题是防止空格/空格。这可以防止任何空间。如果我想在两个单词之间留一个空格怎么办?
      【解决方案7】:

      这与下面对我有用的答案略有不同:

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

      【讨论】:

        【解决方案8】:

        要从输入字段中自动删除所有空格,您需要创建自定义验证器。

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

        它适用于输入和粘贴的文本。

        【讨论】:

        • 我发现这个解决方案是最便携且侵入性最小的。使用反应式表单自己的验证系统。它适用于任何情况,并且可以在所有应用程序中使用。好工作! +1
        • 为什么不直接使用 .trim() 而不是 .spilit(' ').join('')?
        • @Crystal .trim 删除字符串开头和结尾的空格,而 split/join 删除所有空格(并且只有空格,而不是所有空格,例如制表符、换行符)字符串。
        【解决方案9】:

        经过大量试验,我发现 [a-zA-Z\\s]* 表示带有空格的字母数字

        例子:

        纽约

        新德里

        【讨论】:

          【解决方案10】:

          我使用了表单 valueChanges 函数来防止空格。每一个 在所需的验证之后它将修剪所有字段的时间 适用于空白字符串。

          喜欢这里:-

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

          已编辑 --

          如果您在表单控件中使用任何数字/整数,在这种情况下,修剪功能将无法直接工作 像这样使用:

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

          【讨论】:

          • 您仍然可以粘贴空格或使用 Alt+0160
          【解决方案11】:

          另一种方法是使用 Angular 模式验证器并匹配任何非空白字符。

          const nonWhitespaceRegExp: RegExp = new RegExp("\\S");
          
          this.formGroup = this.fb.group({
            name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
          });
          

          【讨论】:

            【解决方案12】:

            我有一个要求,其中 Firstname 和 Lastname 是用户输入,它们是必填字段,并且用户不应将空格作为第一个字符。

            从 node_modules 导入 AbstractControl。

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

            检查第一个字符是否为空格 如果是,则将该值置空并返回所需的值:true。 如果没有返回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;
            }
            }
            

            如果第一个字符是空格,上面的代码会触发错误,并且不允许空格作为第一个字符。

            并在表单构建器组中声明

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

            【讨论】:

              【解决方案13】:

              在 hello.component.html

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

              在 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

              【讨论】:

                【解决方案14】:

                在你的 app.component.html

                <form [formGroup]="signupForm">
                
                           <input  type="text" name="name" [formControl]="signupForm.controls['name']"
                              placeholder="First Name"
                              required
                            />
                     <small
                            *ngIf="signupForm.controls['name'].hasError('pattern')"
                            class="form-error-msg"
                            >First Name without space</small>
                
                    </form>
                

                在您的 app.componen.ts 文件中

                import { Validators, FormGroup, FormControl } from "@angular/forms";
                signupForm: FormGroup;
                ngOnInit(){
                this.signupForm = new FormGroup({
                  name: new FormControl("", [
                    Validators.required,
                    Validators.pattern("^[a-zA-Z]+$"),
                    Validators.minLength(3)
                  ])
                })
                

                【讨论】:

                  【解决方案15】:
                      export function noWhitespaceValidator(control: FormControl) {
                         const isSpace = (control.value || '').match(/\s/g);
                         return isSpace ? {'whitespace': true} : null;
                  }
                  

                  使用

                   password: ['', [Validators.required, noWhitespaceValidator]]
                  

                  在模板/html中

                  <span *ngIf="newWpForm.get('password').hasError('whitespace')">
                      password cannot contain whitespace
                  </span>
                  

                  【讨论】:

                  • 验证空格的最佳和标准方法.. 好在我们可以跨表单组使用这个验证器
                  【解决方案16】:

                  以下指令可以与 Reactive-Forms 一起使用来修剪所有表单字段,以便标准 Validators.required 工作正常:

                  @Directive({
                    selector: '[formControl], [formControlName]',
                  })
                  export class TrimFormFieldsDirective {
                    @Input() type: string;
                  
                    constructor(@Optional() private formControlDir: FormControlDirective, 
                                @Optional() private formControlName: FormControlName) {}
                  
                    @HostListener('blur')
                    @HostListener('keydown.enter')
                    trimValue() {
                      const control = this.formControlDir?.control || this.formControlName?.control;
                      if (typeof control.value === 'string' && this.type !== 'password') {
                        control.setValue(control.value.trim());
                      }
                    }
                  }
                  

                  【讨论】:

                  • 如果您使用的是响应式表单,此解决方案可用于整个应用程序。最佳解决方案。
                  【解决方案17】:

                  要在输入开始时验证空白,您只需调用更改事件并为此执行内联函数。

                  <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/>

                  【讨论】:

                    【解决方案18】:

                    我认为一个简单而干净的解决方案是使用模式验证。

                    以下模式允许字符串以空格开头不允许字符串只包含空格:

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

                    可以在为表单组的相应控件添加验证器时设置:

                    const form = this.formBuilder.group({
                                name: ['', [
                                    Validators.required,
                                    Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
                                ]]
                            });
                    

                    【讨论】:

                    • 简单干净的解决方案:)
                    • Validators.pattern(/[\S]/) 更简洁易读,但也需要至少一个字符。
                    【解决方案19】:

                    如果您在 Angular 2+ 中使用响应式表单,您可以在 (blur) 的帮助下删除前导和尾随空格

                    app.html

                    <input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />
                    

                    app.ts

                    public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
                        if (formControl && formControl.value && typeof formControl.value === 'string') {
                            formControl.setValue(formControl.value.trim());
                        }
                    }
                    

                    【讨论】:

                      【解决方案20】:
                      export function NoWhitespaceValidator(): ValidatorFn {
                          return (control: AbstractControl): any => {
                              window.setTimeout(() => {
                                  if (control.value && control.value != '') {
                                      let trimedvalue = control.value.replace(/\s/g, '');
                                      control.setValue(trimedvalue);
                                  }
                              }, 10);
                          };
                      }
                      
                      
                      username: ['', Validators.compose([Validators.required, NoWhitespaceValidator()])],
                      

                      【讨论】:

                        猜你喜欢
                        • 2021-06-10
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2014-05-11
                        • 1970-01-01
                        • 2018-06-04
                        相关资源
                        最近更新 更多