Angular 8 : Make FormBuilder Accept Numbers Only with Range for Latitude and Longitude

标签 angular typescript angular-material angular-reactive-forms angular8

如何让 FormBuilder 要求数字?

我正在为纬度和经度编写表单构建器。
在这下面,

  • 写入 -91 或 91 将产生验证错误,按预期工作
  • -90 和 90 之间的任何东西都很好。
  • 它接受最多 32 位数字和小数点的数字,也可以使用

  • 问题:
  • 但是,输入字母“Abcd”等不会出现验证错误。

  • 如何解决这个问题?
      'latitude': [null, [Validators.maxLength(32), Validators.min(-90), Validators.max(90)]],
    

    如果可能,最好在表单中进行验证,而不是输入文本框 type=number,

    最佳答案

    您可以使用输入类型编号这将阻止任何字母

    <input type="number" formControlName="latitude" />
    

    使用 Validators.pattern 仅允许数字的另一个选项,如果您输入了无效字符,这会将控件设置为无效。

       latitude: [
            null,
            [
              Validators.maxLength(32),
              Validators.min(-90),
              Validators.max(90),
              Validators.pattern(/\-?\d*\.?\d{1,2}/)
            ]
          ]
    
    

    demo 🚀🚀

    关于 Angular 8 : Make FormBuilder Accept Numbers Only with Range for Latitude and Longitude,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59463163/

    相关文章:

    不同固定大小项目的 Angular 虚拟滚动策略

    Angular 2/Rxjs : do I really need to unsubscribe?

    javascript - 禁用向前操作视频

    angular - @angular/flex-layout 与行和列间距?

    angular - 如何在 Angularjs2 (2.0.1) 中更快地加载 Observable rxjs/Rx lib

    javascript - 如何使用Typescript定义强类型电子邮件模板参数?

    angular - ionic 3 : Uncaught (in promise): ReferenceError: google is not defined ReferenceError

    javascript - 具有现有验证的 Angular 控制值访问器

    angular - 有没有办法在自动完成(Angular 4)中进行多项选择?

    javascript - 当我更改模块时,图标无法正确加载,提示跨源请求