代码之家  ›  专栏  ›  技术社区  ›  Sangwin Gawande

角度4形式验证器-minLength和maxLength不适用于字段类型编号

  •  48
  • Sangwin Gawande  · 技术社区  · 7 年前

    我正在尝试开发一个联系人表单,我希望用户输入长度在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>
    

    this.myForm = this.formBuilder.group({
         phone: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(12)]],
         message: ['',  [Validators.required, Validators.minLength(10), Validators.maxLength(100)]]
    });`
    
    12 回复  |  直到 3 年前
        1
  •  30
  •   Sangwin Gawande    3 年前

    使用方法如下,效果极佳:

    phone: ['',  [Validators.required, Validators.min(10000000000), Validators.max(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;
        };
      }
    }
    
        2
  •  16
  •   Chandru    7 年前

    尝试以下工作示例代码:

    组成部分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>
    

    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)])]
            });
    }
    }
    
        3
  •  13
  •   Nagender Pratap Chauhan    2 年前

    我有一个技巧,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>
    
        4
  •  7
  •   Sajeetharan    7 年前

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

    Angular2 min/max validators

        5
  •  3
  •   aman raj    5 年前

    这个技巧会很有帮助

    .html 文件

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

    .输电系统 文件

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

     Validators.pattern('^[0-9]{2,30}$')
    
        6
  •  3
  •   Fateh Mohamed    4 年前

    你可以使用 图案 而是验证您的电话号码,并将输入类型更改为文本

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

    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>
    
        7
  •  0
  •   Chris Halcrow    6 年前

    number 字段,您可以验证最小值和最大值 价值观 使用内置角度验证,如下所示:

    .输电系统

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

    <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
  •   Sampath Kumar    6 年前

    多个参数或多个条件的形式验证应作为单个验证器组成,否则会出现可观察或承诺错误:

    phone: ['',  Validators.compose([Validators.required,Validators.min(10000000000), Validators.max(999999999999)])],
    
        9
  •  0
  •   laurensdewaele    5 年前

    保持 <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 });
    });
    
        10
  •  -1
  •   Tabish Zaman    7 年前
    <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>
    
        11
  •  -1
  •   Prachi Shah    6 年前

    phone: ['', Validators.compose([
            Validators.required, 
            Validators.minLength(10),
            Validators.maxLength(12)])
          ])],
    
        12
  •  -2
  •   Jitendra G2    6 年前

    使用 Compose() 方法,将多个验证器组合到单个函数中。

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