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

代码如下:

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
    }

谢谢!!!

相关推荐
m0dw2 天前
正则表达式梳理
正则表达式
mortimer3 天前
Python 正则替换陷阱:`\1` 为何变成了 `\x01`?
python·正则表达式
666HZ6663 天前
正则表达式使用示例
javascript·vue.js·正则表达式
一百天成为python专家5 天前
python正则表达式(小白五分钟从入门到精通)
数据库·python·正则表达式·pycharm·python3.11
山烛5 天前
小白学Python,标准库篇——随机库、正则表达式库
开发语言·python·正则表达式·random·re·随机库·正则表达式库
小王爱学人工智能5 天前
正则表达式库和第三方库
正则表达式
之歆7 天前
Python-正则表达式-信息提取-滑动窗口-数据分发-文件加载及分析器-浏览器分析-学习笔记
python·学习·正则表达式
数字芯片实验室7 天前
分享一个可以学习正则表达式的网址:Pythex.org
学习·正则表达式
阿蒙Amon9 天前
C#正则表达式全面详解:从基础到高级应用
开发语言·正则表达式·c#
秋难降9 天前
Python 知识点详解(二)
数据库·python·正则表达式