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

代码如下:

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
    }

谢谢!!!

相关推荐
踏着七彩祥云的小丑3 天前
Go学习第9天:并发编程 + 文件操作 + 正则表达式
学习·golang·正则表达式·go
bosins4 天前
密码复杂度验证正则表达式
正则表达式
小森林之主4 天前
正则表达式零宽断言实战:凌晨3点的服务器报警
python·正则表达式·零宽断言·服务器报警·正则速查
小森林之主4 天前
Python re 模块速查:从实战对比中掌握正则表达式
python·正则表达式·性能测试·re模块·编程实战
程序猿零零漆5 天前
Python进阶之路:正则表达式、高级语法与核心数据结构(链表、二叉树)全解析
数据结构·python·正则表达式
2301_781833526 天前
Python 正则表达式入门教程
开发语言·python·正则表达式
五阿哥永琪7 天前
正则表达式
数据库·mysql·正则表达式
小森林之主7 天前
深入正则表达式:核心语法与实战剖析
javascript·python·正则表达式·编程技巧·字符串处理
小森林之主7 天前
JavaScript 正则表达式:从零开始的实战对比
javascript·正则表达式·前端开发·性能对比·文本处理
不吃土豆的马铃薯7 天前
C++ 正则表达式入门详解
linux·服务器·网络·数据库·c++·正则表达式