Angular 4 个表单验证器 - minLength 和 maxLength 不适用于字段类型编号

Angular 4 Form Validators - minLength & maxLength does not work on field type number

我正在尝试开发联系表,我希望用户输入 phone 长度在 10-12 之间的数值。

值得注意的是,相同的验证正在 Message 字段上进行,它唯一的 number 字段给我带来了麻烦。

I found this answer but it is of no use for me.

我有如下代码:

HTML :

<form [formGroup]="myForm" (ngSubmit)="myFormSubmit()">
      <input type="number" formControlName="phone" placeholder="Phone Number">
      <input type="text" formControlName="message" placeholder="Message">
       <button class="button" type="submit" [disabled]="!myForm.valid">Submit</button>
</form>

TS :

this.myForm = this.formBuilder.group({
     phone: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(12)]],
     message: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(100)]]
});`

你不应该在这里使用长度,对于最小值和最大值使用自定义验证器,

var numberControl = new FormControl("", CustomValidators.number({min: 10000000000, max: 999999999999 }))

Angular2 min/max validators

像下面一样使用它并且工作完美:

phone: ['',  [Validators.required, Validators.min(10000000000), Validators.max(999999999999)]],

自定义验证服务:

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

export class customValidationService {
   static checkLimit(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
        if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
            return { 'range': true };
        }
        return null;
    };
  }
}

试试这个有效的示例代码:

component.html

<div class="container">
    <form [formGroup]="myForm" 
    (ngFormSubmit)="registerUser(myForm.value)" novalidate>
    <div class="form-group" [ngClass]="{'has-error':!myForm.controls['phone'].valid}">
        <label for="phone">Email</label>
        <input type="phone" formControlName="phone" placeholder="Enter Phone" 
        class="form-control">
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('minlength')">
            Your phone must be at least 5 characters long.
        </p>
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('maxlength')">
            Your phone cannot exceed 10 characters.
        </p>
        <p class="alert alert-danger" *ngIf="myForm.controls['phone'].hasError('required') && myForm.controls['phone'].dirty">
            phone is required
        </p>
    </div>
    <div class="form-group text-center">
        <button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>
    </div>
</form>
</div>

component.ts

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

export class AppComponent implements OnInit {
myForm: any;
constructor(
        private formBuilder: FormBuilder
    ) {}

ngOnInit() {
    this.myForm = this.formBuilder.group({
            phone: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
        });
}
}
<div nz-col [nzXs]="24" [nzSm]="12" nz-form-control nzHasFeedback>
                                <nz-input formControlName="password" [nzPlaceHolder]="'password'" [nzType]="'password'" [nzSize]="'large'" (ngModelChange)="validateConfirmPassword()">
                                </nz-input>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('minlength')">Your password must be at least 5 characters long. </div>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('maxlength')">Your password cannot exceed 15 characters. </div>
                                <div nz-form-explain *ngIf="getFormControl('password').dirty&&getFormControl('password').hasError('required')">Please input your password!</div>
                            </div>

对于 number 字段,您可以使用内置 Angular 验证来验证最小和最大 ,如下所示:

.ts

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

private myNumberFieldMin: number = 1;
private myNumberFieldMax: number = 1000000;

constructor() {
      this.myForm = this.formBuilder.group({
        myNumberField
      })

this.myForm.controls.myNumberField.setValidators([
  Validators.min(this.myNumberFieldMin),
  Validators.max(this.myNumberFieldMax)
]);

html

<form [formGroup]="myForm">
  <input type="number" formControlName="myNumberField">

  <div *ngIf="this.myForm.controls['myNumberField'].errors && this.myForm.controls['myNumberField'].errors.min">
    <span class="error-message">Value must be at least {{myNumberFieldMin}}</span>
  </div>
  <div *ngIf="this.myForm.controls['myNumberField'].errors && this.myForm.controls['myNumberField'].errors.max">
    <span class="error-message">Maximum value is {{myNumberFieldMax}}</span>
  </div>
</form>

多个参数或多个条件的表单验证应该作为单个验证器组成,否则您将得到可观察或承诺错误:

phone: ['',  Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],

使用Compose()方法,将多个验证器组合成一个函数。

更新 .TS 文件如下,

this.myForm = this.formBuilder.group({ phone: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(12)])], message: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(100)])] });

如果你想通过多个验证器验证一个字段,你应该试试这个

phone: ['', Validators.compose([
        Validators.required, 
        Validators.minLength(10),
        Validators.maxLength(12)])
      ])],

我有一个 100% 有效的技巧。

定义类型 'text' 而不是 'number' 的输入。

例如:

<input placeholder="OTP" formControlName="OtpUserInput" type="text">

然后使用作为验证一部分的模式。

喜欢:

this.ValidOtpForm = this.formbuilder.group({
             OtpUserInput: new FormControl(
              { value:'', disabled: false },
          [
          Validators.required,
          Validators.minLength(6),
          Validators.pattern('[0-9]')
        ]),
});

这意味着我们定义了适合最小长度的输入类型文本,我们也 为数值定义模式(验证),以便我们可以同时实现 验证。

剩余代码:

<mat-error *ngIf="RegistrationForm.controls['Password'].hasError('minlength')">Use 6 or more characters with a mix of letters</mat-error>
<mat-error *ngIf="ValidOtpForm.controls['OtpUserInput'].hasError('pattern')">Please enter numeric value.</mat-error>

保留 <input type="number" /> 并将 int 值转换为字符串。

const phoneControl: FormControl = this.myForm.controls.phone;

// Do not forget to unsubscribe

phoneControl.valueChanges.subscribe(v => {

  // When erasing the input field, cannot read toString() of null, can occur
  phoneControl.setValue((v && v.toString()) || null, { emitEvent: false });
});

这个技巧会有帮助

.html文件中

 <input type="text" (keyup)="onKeyUp($event)" formControlName="phone" placeholder="Phone Number">

.ts文件中

下面的代码限制字符串字符

    public onKeyUp(event: any) {
    const NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
    let newValue = event.target.value;
    let regExp = new RegExp(NUMBER_REGEXP);

    if (!regExp.test(newValue)) {
      event.target.value = newValue.slice(0, -1);
    }
   }

和其他验证

phone: ['', Validators.compose([
        Validators.required, 
         Validators.pattern('^[0-9]{0,30}$')])
      ])],

以上图案代码最多允许30位数字。 如果你想要最少两位数,你可以这样做

 Validators.pattern('^[0-9]{2,30}$')

您可以使用 模式 来验证您的 phone 号码,并将您的输入类型更改为文本

<input type="text" formControlName="phone" placeholder="Phone Number">

并将此模式用于 phone 长度在 10 到 12 之间的数字

phonePattern = /^[0-9]{10,12}$/;

并更改表单控件上的验证器

phone: ['',  [Validators.required, Validators.pattern(this.phonePattern)]],

并且可以显示错误:

<div *ngIf="myForm.get('phone').invalid">
      <div class="error-message invalid-feedback" *ngIf="myForm.get('phone').hasError('required')">
        required!
      </div>
      <div class="error-message invalid-feedback" *ngIf="myForm.get('phone').hasError('pattern')">
        invalid!
      </div>
</div>