【问题标题】:Angular form to not allow field starting with space角度形式不允许以空格开头的字段
【发布时间】:2020-08-11 09:41:01
【问题描述】:

我正在尝试验证一个开头不允许空格的名称字段,也尝试过这个(Angular Form Input block (space) REGEX),但根本不允许空格。

我有这样的事情:

<mat-error *ngIf="createEditForm.controls['nameCtrl'].hasError('required')">
    Your Name
</mat-error>

也试过这个(How to validate white spaces/empty spaces? [Angular 2]),但它允许字段以空格开头,只是不允许没有字符的空格。

【问题讨论】:

  • 你有什么理由不想修剪字符串值而不是不允许用户输入空格?
  • 您可以使用正则表达式(模式)验证器。
  • @AlfMoh 没有考虑过,它有效!谢谢。
  • 你试图删除多余的空间onblur? onBlur(value) { this.el.value = value.trim(); }

标签: angular


【解决方案1】:

您可以创建自定义验证器:

export function whitespaceValidator(form: FormCntrol): ValidationErrors {
    return form.value.startsWith(" ") ? {whitespace: true} : null;
  }
}

将其添加到您的表单声明中:

createEditForm: FormGroup = new FormGroup({
  nameCtrl: new FormControl('', whitespaceValidator)
})

并将您的 html 更改为:

<mat-error *ngIf="createEditForm.controls['nameCtrl'].hasError('whitespace')">
    Your Name
</mat-error>

【讨论】:

    【解决方案2】:

    更简单的是,避免在开头和结尾使用 3 到 250 个字符之间的空格:

    Validators.pattern("^\\S{1}.{1,248}\\S{1}$")
    

    【讨论】:

      【解决方案3】:

      正如@AlfMoh 所说,我添加了一个修剪验证器。

      import { Component } from '@angular/core';
      import { ValidatorFn, FormControl } from '@angular/forms';
      
      const trimValidator: ValidatorFn = (control: FormControl) => {
        if (control.value.startsWith(' ')) {
          return {
            'trimError': { value: 'control has leading whitespace' }
          };
        }
        if (control.value.endsWith(' ')) {
          return {
            'trimError': { value: 'control has trailing whitespace' }
          };
        }
      
        return null;
      };
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        control = new FormControl('', trimValidator);
      }
      

      工作就像一个魅力

      【讨论】:

        【解决方案4】:

        开头不允许有空格 我们可以通过几个步骤来实现。

        步骤:1 生成自定义验证器服务为

          ng generate service custom-validator
        

        步骤:2

        填充服务
         import { Injectable } from '@angular/core';
        import { FormControl } from '@angular/forms';
        
        @Injectable({
          providedIn: 'root'
        })
        export class CustomValidatorService {
        
          static notAllowedSpaceValidator(control: FormControl) {
            let userInput = control.value;
            if (userInput && userInput.length > 0) {
              if (userInput[0] === " ") {
                return {
                  forbiddenSpace: {
                    value: userInput,
                  },
                };
              }
            } else {
              return null;
            }
          }
        }
        

        第三步我们差不多完成了,现在我们只需要使用这个验证作为

        businessesForm: FormGroup; // declaration
        
         this.businessesForm = fb.group({
              businessName: [
                "",
                [CustomValidatorService.notAllowedSpaceValidator],  // <--- to foucs
              ], 
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多