鸿蒙 - 判断手机号、身份证(正则表达式)

代码如下:

javascript 复制代码
import promptAction from '@ohos.promptAction';

export class RegExpUtils {
  // 手机号正则字符串
  REGEXP_PHONE: string = '((1[3|4|5|7|8][0-9]{9})$)'
  // 身份证正则字符串
  REGEXP_DATE: string = '((0[1-9])|(10|11|12))((0[1-9])|(1[0-9])|(2[0-9])|(30|31))'
  REGEXP_CARD: string = '^(([1-9]{1})([0-9]{5})(18|19|20)[0-9]{2}(' + this.REGEXP_DATE + '))([0-9]{4})|([0-9]{3}(x|X))$'

  /*
   *  判断姓名
   * */
  checkName(name: string): boolean {
    if (name.length === 0) {
      promptAction.showToast({
        message: '请输入您的姓名',
        bottom: 100,
        duration: 1000
      })
      return false
    }
    return true
  }

  /*
   * 手机号正则
   * */
  checkPhone(phoneNumber: string): boolean {

    if (phoneNumber.length === 0) {
      promptAction.showToast({
        message: '请输入您的手机号码',
        bottom: 100,
        duration: 1000
      })
      return false
    }
    let reg: RegExp = new RegExp(this.REGEXP_PHONE);

    if (!reg.test(phoneNumber)) {
      promptAction.showToast({
        message: '请输入正确格式 11 位手机号码',
        bottom: 100,
        duration: 1000
      })
      return false
    }
    return true
  }

  /*
   * 身份证正则
   * */
  checkIdCard(idcard: string,): boolean {

    if (idcard.length === 0) {
      promptAction.showToast({
        message: '请输入您的身份证号码',
        bottom: 100,
        duration: 1000
      })
      return false
    }

    let reg = RegExp(this.REGEXP_CARD);

    if (idcard.length != 18 || !reg.test(idcard)) {
      promptAction.showToast({
        message: '请输入正确身份证号码',
        bottom: 100,
        duration: 1000
      })
      return false
    }
    return true
  }
}

使用案例:

javascript 复制代码
 if (!this.regExpUtils.checkIdCard(this.savePassengerModel.passengerCardId ?? "")) {
     return
    }     


 if (!this.regExpUtils.checkPhone(this.savePassengerModel.passengerPhone ?? "")) {
    return
    }

谢谢!!!

相关推荐
水木流年追梦18 小时前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
IT大白鼠2 天前
2019年Cloudflare全球宕机事件技术分析:正则表达式回溯失控与互联网基础设施脆弱性研究
运维·正则表达式·去中心化
XMYX-04 天前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
XMYX-04 天前
32 - Go 正则表达式:从匹配字符串到理解 RE2 引擎
golang·正则表达式
程序员榴莲5 天前
Python 正则表达式入门:从匹配手机号到提取文本内容
python·正则表达式
红茶要加冰6 天前
七、正则表达式
linux·运维·正则表达式·shell
Pocker_Spades_A6 天前
Python快速入门专业版(五十八)——正则表达式(re):爬虫文本提取利器(从语法到实战)
爬虫·python·正则表达式
红茶要加冰7 天前
九、文本处理三剑客——sed
linux·运维·服务器·正则表达式·shell
Bug-制造者7 天前
正则表达式 vs Shell通配符:彻底分清,告别命令行踩坑
linux·正则表达式
剑神一笑9 天前
Linux top 命令深度解析:进程监控的性能优化实战
linux·运维·正则表达式