46

I am trying to develop a contact form, I want user to enter phone number values between length 10-12.

Notably same validation is working on Message field, Its only number field which is giving me trouble.

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

I have code like following :

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

12 回答 12

27

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

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;
    };
  }
}
于 2017-09-09T11:02:56.623 回答
15

试试这个工作示例代码:

组件.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>

组件.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)])]
        });
}
}
于 2017-09-09T11:14:36.377 回答
10

我有一个 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 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>
于 2019-01-04T11:07:24.260 回答
7

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

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

Angular2 min/max validators

于 2017-09-09T10:46:33.990 回答
3

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

<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>
于 2020-06-17T15:49:14.580 回答
2

这个技巧会有帮助

.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}$')
于 2020-04-06T08:22:15.910 回答
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 });
});
于 2019-06-28T14:14:29.503 回答
0

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

.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>
于 2018-09-26T01:17:03.523 回答
0

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

phone: ['',  Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],
于 2018-09-30T14:26:06.637 回答
-1

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

phone: ['', Validators.compose([
        Validators.required, 
        Validators.minLength(10),
        Validators.maxLength(12)])
      ])],
于 2018-12-08T14:56:38.223 回答
-1
<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>
于 2018-04-23T11:14:58.923 回答
-2

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

于 2018-10-16T09:28:02.013 回答