我正在try 开发一个联系人表单,我希望用户输入长度在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)]]
});`

推荐答案

像下面这样使用它,效果非常好:

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

Typescript相关问答推荐

如何在不使用变量的情况下静态判断运算式的类型?

如何传递基于TypScript中可变类型的类型?

使用前的组件渲染状态更新

如何使打包和拆包功能通用?

使用`renderToPipeableStream`时如何正确恢复服务器端Apollo缓存?

如何在LucideAngular 添加自定义图标以及如何使用它们

我可以为情态车使用棱角形的路由守卫吗?

带switch 的函数的返回类型的类型缩小

如何将泛型对象作为返回类型添加到类型脚本中

类型推断对React.ForwardRef()的引用参数无效

从非文字数组(object.keys和array.map)派生联合类型

Typescript -返回接口中函数的类型

为什么发送空字段?

使用ngfor循环时,数据未绑定到表

基于未定义属性的条件属性

基于泛型的类型脚本修改类型

基于闭包类型缩小泛型类型脚本函数的范围

如何在TypeScript中描述和实现包含特定属性的函数?

TS 排除带点符号的键

如何在由函数参数推断的记录类型中具有多个对象字段类型