【问题标题】:Is it possible to modify a pattern Validator to include removing blank spaces written in an input field?是否可以修改模式验证器以包括删除输入字段中写入的空格?
【发布时间】:2020-02-05 11:25:41
【问题描述】:

我有一个正在运行的验证器,我在其中检查输入的手机格式是否与后端请求的信息兼容。 是否可以修改此正则表达式,以便删除或不考虑是否在输入的数字之间写入空格? 这是我的验证器

    this.formGroup = this.fb.group({

      mobilePhone: [
        '',
        [
          Validators.required,
          CustomValidators.patternValidator(/^((\+)33|0|0033)[1-9](\d{2}){4}$/, { onlyNumber: true })
        ]
      ],
...


提前谢谢你?

【问题讨论】:

  • 只需在其他子模式的开头、结尾和中间添加\s*

标签: regex angular requiredfieldvalidator customvalidator


【解决方案1】:

正则表达式:

/^(\+\d{1,3}[- ]?)?\d{10}$/

您可以在 regex101.com 上创建正则表达式并进行测试 Here i have done for mobile number validation

如果 Regex 不起作用,那么您可以像这样创建手机号码验证服务:

服务文件(validaion.service.ts)

import * as PhoneNumber from 'awesome-phonenumber';

 static mobileNumberValidator(control) {
    const mobile = new PhoneNumber.default(control.value, 'US');
    return (!mobile.isValid() || !mobile.isMobile()) ? { invalidMobile: false } : null;
  }

TS 文件

mobileNumber: ['', [Validators.required, 
Validators.maxLength(13), ValidationService.mobileNumberValidator]],

HTML

<p class="error" *ngIf="editProfileForm.get('mobileNumber').touched && yourformName['mobileNumber'].errors ">
<span class="error-message" 
*ngIf="!editProfile['mobileNumber'].errors.required && !editProfile.mobileNumber.errors.invalidMobile">
Cell phone number is not valid</span>
 </p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 2021-03-03
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2017-10-30
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多