一、基本概念
uniapp表單校驗是指在用戶提交表單前進行數據格式檢查,以保證數據的正確性和完整性,防止用戶非法提交數據。表單校驗通常包括以下幾種類型:
1、非空驗證:判斷輸入框輸入內容是否為空,如果為空則提示錯誤信息;
2、數據格式驗證:判斷輸入框輸入內容是否符合指定的數據格式,比如郵箱、電話號碼、身份證號碼等;
3、數據範圍驗證:判斷輸入框輸入內容是否在指定範圍內,比如年齡、金額等。
uniapp提供了表單校驗的方法,我們可以使用這些方法來完成表單校驗的功能。
二、示例代碼
以下是一個基本的表單校驗示例:
<template>
<div>
<form @submit="submit">
<div>
<label>姓名</label>
<input type="text" v-model="name" />
</div>
<div>
<label>年齡</label>
<input type="number" v-model="age" />
</div>
<div>
<label>郵箱</label>
<input type="email" v-model="email" />
</div>
<button type="submit">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
age: '',
email: ''
}
},
methods: {
submit() {
// 驗證姓名是否為空
if (this.name.trim() === '') {
uni.showToast({
title: '姓名不能為空',
icon: 'none'
})
return
}
// 驗證年齡是否為數字
if (isNaN(this.age)) {
uni.showToast({
title: '年齡必須為數字',
icon: 'none'
})
return
}
// 驗證郵箱格式
var reg = /^[a-z0-9]+@[a-z0-9]+\.[a-z]{2,4}$/
if (!reg.test(this.email)) {
uni.showToast({
title: '郵箱格式不正確',
icon: 'none'
})
return
}
// 提交數據
}
}
}
</script>
三、常用校驗方法
uniapp提供了一些常用的表單校驗方法,可以方便我們完成表單校驗的功能,以下是常用的表單校驗方法:
1、非空驗證:
if (this.name.trim() === '') {
uni.showToast({
title: '姓名不能為空',
icon: 'none'
})
return
}
2、數據格式驗證:
// 驗證郵箱格式
var reg = /^[a-z0-9]+@[a-z0-9]+\.[a-z]{2,4}$/
if (!reg.test(this.email)) {
uni.showToast({
title: '郵箱格式不正確',
icon: 'none'
})
return
}
3、數據範圍驗證:
// 驗證年齡是否在18-50歲之間
if (this.age 50) {
uni.showToast({
title: '年齡必須在18-50歲之間',
icon: 'none'
})
return
}
四、自定義校驗方法
在實際開發中,我們可能需要對一些特殊的數據格式進行校驗,這時我們可以自定義校驗方法來完成校驗功能。
自定義校驗方法通常包含以下幾個步驟:
1、編寫正則表達式;
2、在校驗方法中使用正則表達式進行數據格式校驗;
3、調用自定義校驗方法實現數據格式校驗。
以下是一個自定義校驗方法的示例代碼:
<template>
<div>
<form @submit="submit">
<div>
<label>手機號碼</label>
<input type="text" v-model="mobile" />
</div>
<button type="submit">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
mobile: ''
}
},
methods: {
// 自定義校驗方法
checkMobile() {
var reg = /^1[3|4|5|7|8][0-9]{9}$/
if (!reg.test(this.mobile)) {
uni.showToast({
title: '手機號碼格式不正確',
icon: 'none'
})
return false
}
return true
},
submit() {
// 調用自定義校驗方法
if (!this.checkMobile()) {
return
}
// 提交數據
}
}
}
</script>
五、結語
表單校驗是我們在開發中經常使用的功能,uniapp 提供了豐富的表單校驗方法,可以方便我們完成表單校驗的功能。同時,我們也可以根據開發需求自定義表單校驗方法,以便完成更靈活的表單校驗功能。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/242704.html
微信掃一掃
支付寶掃一掃