Angular 4表单验证器-minLength& maxLength不适用于字段类型编号 [英] Angular 4 Form Validators - minLength & maxLength does not work on field type number

查看:210
本文介绍了Angular 4表单验证器-minLength& maxLength不适用于字段类型编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发联系表格,我希望用户输入长度在10到12之间的电话号码.

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

消息字段上进行的验证非常明显,它的唯一 number 字段给我带来了麻烦.

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

我找到了这个答案,但这对于没有用我.

我有如下代码:

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

推荐答案

更新1:

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


像下面那样使用它,并且效果很好:


Used it like following and worked perfectly :

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

这篇关于Angular 4表单验证器-minLength&amp; maxLength不适用于字段类型编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆