一、前置准备-学习正则表达式
正则表达式是用于匹配字符串中字符组合的模式(规则)
日常开发中主要用来做三件事:匹配、替换、提取
- 手机号表单要求用户只能输入11位的数字 (匹配)
- 过滤掉页面内容中的一些敏感词(替换)
- 从字符串中获取我们想要的特定部分(提取)等
基本使用:1.定义正则 2.使用正则
//定义正则
// 方式 1:简写
const res1: RegExp = /ArkTS/
// 方式 2:通过实例化的方式创建
const reg2: RegExp = new RegExp('ArkTS')
//使用正则
//如果正则表达式与指定的字符串匹配 ,返回true,否则false
let str:string = 'ArkTS'
console.log('web:', res.test('ArkTS')) // true
console.log('web:', res.test('Java')) // false
日常开发中使用正则的时候一般会寻找现成的正则直接调用,我们只需掌握他的用法。接下来根据案例为大家准备了两个正则,分别用来校验手机号和验证码的格式。
二、用户校验信息案例
需求:
- 点击登录:手机号和验证码格式校验
-
- 手机号 /^(?:(?:+|00)86)?1\d{10}$/
- 验证码:6 位,字母+数字 /^\d{6}$/
- 请提示弹窗提示用户
步骤分析
- 获取用户输入信息
用户在TextInput输入框输入内容,通过状态变量获取到用户输入内容(参数text),该参数支持$$双向绑定。
2.正则判断
1.点击登录按钮时注册onClick事件,登陆前需要通过正则判断对用户输入的内容进行验证。
2.使用正则判断reg.test(验证的内容)验证是否符合,返回布尔类型,如果正则表达式与验证的内容匹配则返回true,否则返回false。
3.通过if判断来验证手机号,如果不符合正则表达式则return中断下面代码的执行,并轻提示用户'输入正确的手机号',符合则直接通过。进入下一项验证码判断,验证码判断与手机号判断同理。
3.最终两项都符合要求,验证通过使用轻提示弹窗提示'登录成功'
4.轻提示弹窗使用步骤
1.导入模块:import { promptAction } from '@kit.ArkUI';
2.使用弹窗:promptAction.showToast({ options:ShowToastOptions文本弹窗选项(必填)})
3.参数介绍:message显示文本说明(必填)、duration设置显示时长,默认1500ms(选填)
4.用在onClick事件中,当事件触发则开启弹窗。
5.promptAction.showToast({ message:'提示内容' , duration:1500 })
@Entry
@Component
struct LoginDemo {
@State time: number = 0
@State phone: string = ''
@State code: string = ''
build() {
Column() {
this.titleBuilder()
TextInput({ placeholder: '请输入手机号', text: $$this.phone })
.textInputExtend()
Divider()
Row() {
TextInput({ placeholder: '请输入验证码', text: $$this.code })
.textInputExtend()
.layoutWeight(1)
Text(this.time == 0 ? '发送验证码' : `${this.time}秒后获取`)
.fontSize(14)
.fontColor(Color.Gray)
.onClick(() => {
// 避免倒计时 为 0 时,重复点击
if (this.time != 0) {
return
}
this.time = 60 //注意:测试时修改这里的number可以避免等待较长时间
const timeId = setInterval(() => {
this.time--
// 倒计时结束,清空定时器
if (this.time == 0) {
clearInterval(timeId)
}
}, 1000)
//定时器清除后通过setTimeout延时两秒执行随机数
setTimeout(() => {
AlertDialog.show({ //通过UI弹窗的方式将4位随机数显示
message: Math.floor(1000 + 9000 * Math.random())
.toString()
})
}, 2000)
})
}
.width('100%')
Divider()
Button('登录')
.width('100%')
.type(ButtonType.Normal)
.backgroundColor('#ea6051')
.margin({ top: 50 })
.onClick(() => {
const reg1 = /^(?:(?:\+|00)86)?1\d{10}$/
const reg2 = /^\d{6}$/
if (reg1.test(this.phone) == false) {
AlertDialog.show({
message: '手机号有误'
})
return
}
if (reg2.test(this.code) == false) {
AlertDialog.show({
message: '验证码有误'
})
}
})
AlertDialog.show({
message: '登陆成功'
})
}
.padding({ top: 80, left: 40, right: 40 })
.width('100%')
.alignItems(HorizontalAlign.Start)
}
@Builder
titleBuilder() {
Text('短信登录')
.fontSize(25)
.fontWeight(600)
.margin({ bottom: 30 })
}
}
@Extend(TextInput)
function textInputExtend() {
.backgroundColor(Color.White)
.padding({ left: 0, top: 20, bottom: 20 })
.placeholderColor('#ccc')
}