Angular 4 Form Validators - minLength& maxLength不适用于字段类型编号

时间:2017-09-09 10:31:16

标签: forms angular validation angular4-forms

我正在尝试开发一个联系表单,我希望用户输入长度为10-12的电话号码。

值得注意的是,同样的验证工作在消息字段,它只有数字字段,这给我带来了麻烦。

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)]]
});`

12 个答案:

答案 0 :(得分:11)

更新1:

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

像下面这样使用它并完美地工作:

 phone: ['',  [Validators.required, customValidationService.checkLimit(10000000000,999999999999)]],

customValidationService:

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

答案 1 :(得分:6)

试试这个工作示例代码:

<强> 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)])]
        });
}
}

答案 2 :(得分:4)

我有个技巧,就是100%可以工作。

定义类型为“文本”而不​​是“数字”的输入。

例如:

<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 8 or more characters with a mix of letters</mat-error>
<mat-error *ngIf="ValidOtpForm.controls['OtpUserInput'].hasError('pattern')">Please enter numeric value.</mat-error>

答案 3 :(得分:3)

你不应该在这里使用长度,因为min和max使用这样的自定义验证器,

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

<强> Angular2 min/max validators

答案 4 :(得分:1)

此技巧会有所帮助

.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}$')

答案 5 :(得分:1)

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

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

并将此模式用于电话号码,长度在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>

答案 6 :(得分:0)

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

答案 7 :(得分:0)

对于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>

答案 8 :(得分:0)

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

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

答案 9 :(得分:0)

使用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)])] });

答案 10 :(得分:0)

如果您想由多个验证者验证字段,则应尝试

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

答案 11 :(得分:0)

保留<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 });
});