移动浏览器中的验证文本字段不起作用

问题描述 投票:0回答:2
  • 移动浏览器中的文本框验证不适用于我的 Angular 应用程序
  • 移动浏览器: Chrome,三星浏览器(不能在两种浏览器中工作)
  • 预期 0 到 9A 到 Z only 在文本字段中

我用过:

1。首先我尝试通过使用 charCode of key 来验证它,用于笔记本电脑 浏览器它工作但对于移动浏览器它没有工作。

手机浏览器字符编码为每个键229,所以没有 工作

代码

HTML

<input (keypress)="numberOnly($event)" type="text" />

TS

numberOnly(event): boolean {
    const charCode = event.which ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;
  }

2。其次我创建了一个指令,并在指令的帮助下尝试验证,这在移动浏览器中再次对我不起作用,在笔记本电脑浏览器中它正在工作。

指令代码:

import { Directive, HostListener, ElementRef, Input } from '@angular/core';
@Directive({
  selector: '[specialIsAlphaNumeric]'
})
export class SpecialCharacterDirective {

  regexStr = '^[a-zA-Z0-9_]*$';
  @Input() isAlphaNumeric: boolean;

  constructor(private el: ElementRef) { }


  @HostListener('keypress', ['$event']) onKeyPress(event) {
    return new RegExp(this.regexStr).test(event.key);
  }

  @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
    this.validateFields(event);
  }

  validateFields(event) {
    setTimeout(() => {

      this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g, '').replace(/\s/g, '');
      event.preventDefault();

    }, 100)
  }

}

3。第三我使用了模式,但它再次在移动浏览器中不起作用,在笔记本电脑浏览器中它可以工作

我使用的模式: /[A-Z]{5}\d{4}[A-Z]{1}/i 我创建了一个反应式表单,然后使用 Validator.pattern

进行了验证
username: ['', Validators.pattern('/[A-Z]{5}\d{4}[A-Z]{1}/i')],}) 

HTML

<input  formcontrolname='username' (keypress)="numberOnly($event)" type="text" />

游乐场: https://codesandbox.io/embed/dazzling-hellman-pygp1?file=/src/app/app.component.html:64-119&codemirror=1

javascript angularjs regex angular-reactive-forms angular-forms
2个回答

0
投票

确保在移动浏览器设置中启用了 JavaScript!

参考: 客户端验证不适用于移动设备

© www.soinside.com 2019 - 2024. All rights reserved.