微信提示在客户端提交验证_微信小程序之表单验证

本文介绍了微信小程序中实现表单验证的类`WxValidate`,包括初始化数据、默认提示信息、验证方法等。该类包含各种常见的验证规则,如必填、邮箱、电话、URL、日期等,并提供了自定义验证方法的接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 /**2 * 表单验证3 *4 * @param {Object} rules 验证字段的规则5 * @param {Object} messages 验证字段的提示信息6 *7 */

8 class WxValidate {9 constructor(rules = {}, messages ={}) {10 Object.assign(this, {11 data: {},12 rules,13 messages,14 })15 this.__init()16 }17

18 /**19 * __init20 */

21 __init() {22 this.__initMethods()23 this.__initDefaults()24 this.__initData()25 }26

27 /**28 * 初始化数据29 */

30 __initData() {31 this.form ={}32 this.errorList =[]33 }34

35 /**36 * 初始化默认提示信息37 */

38 __initDefaults() {39 this.defaults ={40 messages: {41 required: '这是必填字段。',42 email: '请输入有效的电子邮件地址。',43 tel: '请输入11位的手机号码。',44 url: '请输入有效的网址。',45 date: '请输入有效的日期。',46 dateISO: '请输入有效的日期(ISO),例如:2009-06-23,1998/01/22。',47 number: '请输入有效的数字。',48 digits: '只能输入数字。',49 idcard: '请输入18位的有效身份证。',50 equalTo: this.formatTpl('输入值必须和 {0} 相同。'),51 contains: this.formatTpl('输入值必须包含 {0}。'),52 minlength: this.formatTpl('最少要输入 {0} 个字符。'),53 maxlength: this.formatTpl('最多可以输入 {0} 个字符。'),54 rangelength: this.formatTpl('请输入长度在 {0} 到 {1} 之间的字符。'),55 min: this.formatTpl('请输入不小于 {0} 的数值。'),56 max: this.formatTpl('请输入不大于 {0} 的数值。'),57 range: this.formatTpl('请输入范围在 {0} 到 {1} 之间的数值。'),58 }59 }60 }61

62 /**63 * 初始化默认验证方法64 */

65 __initMethods() {66 const that = this

67 that.methods ={68 /**69 * 验证必填元素70 */

71 required(value, param) {72 if (!that.depend(param)) {73 return 'dependency-mismatch'

74 } else if (typeof value === 'number') {75 value =value.toString()76 } else if (typeof value === 'boolean') {77 return !0

78 }79

80 return value.length > 0

81 },82 /**83 * 验证电子邮箱格式84 */

85 email(value) {86 return that.optional(value) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)87 },88 /**89 * 验证手机格式90 */

91 tel(value) {92 return that.optional(value) || /^1[34578]\d{9}$/.test(value)93 },94 /**95 * 验证URL格式96 */

97 url(value) {98 return that.optional(value) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)

99 },100 /**101 * 验证日期格式102 */

103 date(value) {104 return that.optional(value) || !/Invalid|NaN/.test(newDate(value).toString())105 },106 /**107 * 验证ISO类型的日期格式108 */

109 dateISO(value) {110 return that.optional(value) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)111 },112 /**113 * 验证十进制数字114 */

115 number(value) {116 return that.optional(value) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)117 },118 /**119 * 验证整数120 */

121 digits(value) {122 return that.optional(value) || /^\d+$/.test(value)123 },124 /**125 * 验证身份证号码126 */

127 idcard(value) {128 return that.optional(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)129 },130 /**131 * 验证两个输入框的内容是否相同132 */

133 equalTo(value, param) {134 return that.optional(value) || value ===that.data[param]135 },136 /**137 * 验证是否包含某个值138 */

139 contains(value, param) {140 return that.optional(value) || value.indexOf(param) >= 0

141 },142 /**143 * 验证最小长度144 */

145 minlength(value, param) {146 return that.optional(value) || value.length >=param147 },148 /**149 * 验证最大长度150 */

151 maxlength(value, param) {152 return that.optional(value) || value.length <=param153 },154 /**155 * 验证一个长度范围[min, max]156 */

157 rangelength(value, param) {158 return that.optional(value) || (value.length >= param[0] && value.length <= param[1])159 },160 /**161 * 验证最小值162 */

163 min(value, param) {164 return that.optional(value) || value >=param165 },166 /**167 * 验证最大值168 */

169 max(value, param) {170 return that.optional(value) || value <=param171 },172 /**173 * 验证一个值范围[min, max]174 */

175 range(value, param) {176 return that.optional(value) || (value >= param[0] && value <= param[1])177 },178 }179 }180

181 /**182 * 添加自定义验证方法183 * @param {String} name 方法名184 * @param {Function} method 函数体,接收两个参数(value, param),value表示元素的值,param表示参数185 * @param {String} message 提示信息186 */

187 addMethod(name, method, message) {188 this.methods[name] =method189 this.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]190 }191

192 /**193 * 判断验证方法是否存在194 */

195 isValidMethod(value) {196 let methods =[]197 for (let method in this.methods) {198 if (method && typeof this.methods[method] === 'function') {199 methods.push(method)200 }201 }202 return methods.indexOf(value) !== -1

203 }204

205 /**206 * 格式化提示信息模板207 */

208 formatTpl(source, params) {209 const that = this

210 if (arguments.length === 1) {211 return function() {212 let args =Array.from(arguments)213 args.unshift(source)214 return that.formatTpl.apply(this, args)215 }216 }217 if (params ===undefined) {218 returnsource219 }220 if (arguments.length > 2 && params.constructor !==Array) {221 params = Array.from(arguments).slice(1)222 }223 if (params.constructor !==Array) {224 params =[params]225 }226 params.forEach(function(n, i) {227 source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function() {228 returnn229 })230 })231 returnsource232 }233

234 /**235 * 判断规则依赖是否存在236 */

237 depend(param) {238 switch (typeofparam) {239 case 'boolean':240 param =param241 break

242 case 'string':243 param = !!param.length244 break

245 case 'function':246 param =param()247 default:248 param = !0

249 }250 returnparam251 }252

253 /**254 * 判断输入值是否为空255 */

256 optional(value) {257 return !this.methods.required(value) && 'dependency-mismatch'

258 }259

260 /**261 * 获取自定义字段的提示信息262 * @param {String} param 字段名263 * @param {Object} rule 规则264 */

265 customMessage(param, rule) {266 const params = this.messages[param]267 const isObject = typeof params === 'object'

268 if (params && isObject) returnparams[rule.method]269 }270

271 /**272 * 获取某个指定字段的提示信息273 * @param {String} param 字段名274 * @param {Object} rule 规则275 */

276 defaultMessage(param, rule) {277 let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]278 let type = typeofmessage279

280 if (type === 'undefined') {281 message = `Warning: No message defined for${rule.method}.`282 } else if (type === 'function') {283 message = message.call(this, rule.parameters)284 }285

286 returnmessage287 }288

289 /**290 * 缓存错误信息291 * @param {String} param 字段名292 * @param {Object} rule 规则293 * @param {String} value 元素的值294 */

295 formatTplAndAdd(param, rule, value) {296 let msg = this.defaultMessage(param, rule)297

298 this.errorList.push({299 param: param,300 msg: msg,301 value: value,302 })303 }304

305 /**306 * 验证某个指定字段的规则307 * @param {String} param 字段名308 * @param {Object} rules 规则309 * @param {Object} data 需要验证的数据对象310 */

311 checkParam(param, rules, data) {312

313 //缓存数据对象

314 this.data =data315

316 //缓存字段对应的值

317 const value = data[param] !== null && data[param] !== undefined ? data[param] : ''

318

319 //遍历某个指定字段的所有规则,依次验证规则,否则缓存错误信息

320 for (let method inrules) {321

322 //判断验证方法是否存在

323 if (this.isValidMethod(method)) {324

325 //缓存规则的属性及值

326 const rule ={327 method: method,328 parameters: rules[method]329 }330

331 //调用验证方法

332 const result = this.methods[method](value, rule.parameters)333

334 //若result返回值为dependency-mismatch,则说明该字段的值为空或非必填字段

335 if (result === 'dependency-mismatch') {336 continue

337 }338

339 this.setValue(param, method, result, value)340

341 //判断是否通过验证,否则缓存错误信息,跳出循环

342 if (!result) {343 this.formatTplAndAdd(param, rule, value)344 break

345 }346 }347 }348 }349

350 /**351 * 设置字段的默认验证值352 * @param {String} param 字段名353 */

354 setView(param) {355 this.form[param] ={356 $name: param,357 $valid: true,358 $invalid: false,359 $error: {},360 $success: {},361 $viewValue: ``,362 }363 }364

365 /**366 * 设置字段的验证值367 * @param {String} param 字段名368 * @param {String} method 字段的方法369 * @param {Boolean} result 是否通过验证370 * @param {String} value 字段的值371 */

372 setValue(param, method, result, value) {373 const params = this.form[param]374 params.$valid =result375 params.$invalid = !result376 params.$error[method] = !result377 params.$success[method] =result378 params.$viewValue =value379 }380

381 /**382 * 验证所有字段的规则,返回验证是否通过383 * @param {Object} data 需要验证数据对象384 */

385 checkForm(data) {386 this.__initData()387

388 for (let param in this.rules) {389 this.setView(param)390 this.checkParam(param, this.rules[param], data)391 }392

393 return this.valid()394 }395

396 /**397 * 返回验证是否通过398 */

399 valid() {400 return this.size() === 0

401 }402

403 /**404 * 返回错误信息的个数405 */

406 size() {407 return this.errorList.length408 }409

410 /**411 * 返回所有错误信息412 */

413 validationErrors() {414 return this.errorList415 }416 }417

418 export default WxValidate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值