vue批量判定數據是否合規 主要用於數據的提交,批量判定是否有數據是否和規則 姓名: 年齡: ... ...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>vue批量判定數據是否合規</title> </head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <body> <div id="app"> <p>主要用於數據的提交,批量判定是否有數據是否和規則</p> <ul> <li> 姓名: <input type="text" v-model="name"> </li> <li> 年齡: <input type="number" v-model="age"> </li> <li> 體重: <input type="number" v-model="weight"> </li> <li> 手機: <input type="phone" v-model="phone"> </li> <li> 郵箱: <input type="email" v-model="email"> </li> <li> 地址: <input type="text" v-model="address"> </li> </ul> <button @click="btn()">點擊測試數據是否正確</button> </div> <script> var app = new Vue({ el: '#app', data: { name: '', age: '', weight: '', phone: '', email: '', address: '' }, methods: { // 判定是否合規 have_empty: function (arr) { for (let key in arr) { console.log(arr[key].inspect) if (arr[key].inspect) { // 有值並且有規則執行驗證 if(arr[key].reg){ let reg = new RegExp(arr[key].reg) var red_end = reg.test(arr[key].inspect) if( !red_end ){ alert('請輸入正確的' + arr[key].msg) return false } } }else{ // 沒值返回 fasle alert('請輸入' + arr[key].msg) return false } } return true }, // 判定規則前傳入參數 inspect: function () { var end = this.have_empty([ { inspect: this.name, // 待檢測的欄位 msg: '姓名', // 空值返回的提示 }, { inspect: this.age, msg: '年齡' }, { inspect: this.weight, msg: '體重' }, { inspect: this.phone, msg: '手機號', reg: '^[1][3,4,5,7,8][0-9]{9}$' }, { inspect: this.email, msg: '郵箱', reg: '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$' }, { inspect: this.address, msg: '地址' } ]) console.log(end) if (!end) return // 判定驗證結果 console.log('執行提交的ajax函數') }, btn: function () { this.inspect() } }, mounted () { }, }) </script> </body> </html>