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

代码如下:

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
    }

谢谢!!!

相关推荐
前端世界1 天前
Python 正则表达式实战:用 Match 对象轻松解析拼接数据流
python·正则表达式·php
Edward.W2 天前
别再和正则表达式死磕了!这套AI工具集让你的开发效率翻倍⚙️[特殊字符]
人工智能·正则表达式
beijingliushao2 天前
58-正则表达式
数据库·python·mysql·正则表达式
雷达学弱狗2 天前
正则表达式,字符串的搜索与替换
正则表达式
良木林2 天前
JS中正则表达式的运用
前端·javascript·正则表达式
ComputerInBook2 天前
C++编程语言:标准库:第37章——正则表达式(Bjarne Stroustrup)
开发语言·c++·正则表达式
雷达学弱狗2 天前
正则表达式与转义符的区别。注意输入的东西经过了一次转义,一次正则表达式。\\转义是单斜杠\\在正则表达式也是单斜杠所以\\\\经过两道门才是字符单斜杠
正则表达式
Zzz_睡不醒4 天前
JS(正则表达式)
javascript·正则表达式·c#
啊啊啊啊8434 天前
函数,数组与正则表达式
前端·chrome·正则表达式
MediaTea4 天前
Python:正则表达式
开发语言·c++·python·正则表达式