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

代码如下:

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
    }

谢谢!!!

相关推荐
XYiFfang5 小时前
【MYSQL】SQL学习指南:从常见错误到高级函数与正则表达式
sql·mysql·正则表达式·regexp_like·group_concat
czhc11400756632 天前
Linux108 shell:.bashrc 正则表达式:. * .* ^ $ ^$ [ ] [^] ^[] ^[^ ] \< \>
linux·正则表达式
数据知道2 天前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
利刃大大2 天前
【高并发服务器】三、正则表达式的使用
服务器·c++·正则表达式·项目
尘觉5 天前
正则表达式入门与进阶(优化版)
正则表达式
AI悦创|编程1v16 天前
00-1-正则表达式学习心得:从入门到上瘾,再到克制
数据仓库·正则表达式·数据挖掘·ai悦创编程一对一教学·python一对一辅导·python一对一教学
带土17 天前
PHP 中的正则表达式
正则表达式·php
taller_20007 天前
VBA之正则表达式(45)-- 拆分材料和规格
正则表达式·正则·数据清洗·提取数据·材料规格
光明磊7 天前
正则表达式Regex
正则表达式