Home > WeChat Applet > Mini Program Development > Example of implementation of form verification function in WeChat applet

Example of implementation of form verification function in WeChat applet

黄舟
Release: 2017-09-12 09:25:36
Original
2930 people have browsed it

What is the most difficult public business to implement in WeChat mini programs? It should be form verification. This article mainly introduces how the WeChat applet implements the form verification function. It has certain reference value. Interested friends can refer to

Mini Program SDK version 1.4

Difficulties in form verification

If you want to ask what is the most difficult public business to implement in WeChat mini programs? It should be form verification, nothing else. The reasons are as follows:

The number of form components reaches 11, ranking first among all types of components. Fortunately, not all of them need to be verified.
The operation methods of these components are diverse, which can be divided into sliding, (multi-line) input, clicking, and clicking + sliding.
Even if it is the same component, there will be different verification rules due to different business scenarios.
What’s even more troublesome is that these components are often linked or associated with each other for verification.

However, as a non-simple static page, there is a small program with a lot of user interaction, and form verification is a very common function: login, registration, new addition, editing…

In short: Diversity of form components

Try componentization


If you pay attention to the front-end development trend in recent years, you will definitely think of "componentization" to achieve:

The views, styles, and validation logic of each form component are encapsulated into separate business components and then called directly.

But things don’t seem to be that simple.

If we consider abstracting n native components, adding n verification rules, and then multiplying by n (full arrangement) of the relationship between components, the complexity will reach at least n³.

And each component’s verification failure or success must notify the parent component so that the error message can be displayed or the next step can be performed.

Not only does this not solve the problem, but it also makes these public form components too complex and confusingly coupled.

Try non-componentization


Since the original idea doesn’t work, let’s go back to the starting point and see what our core needs to be abstracted .

It’s nothing more than two things: the element style of the view layer and the verification rules of the logic layer.

As mentioned above, encapsulating native form components will greatly increase the complexity. Simply abandon it, and the complexity can be reduced to n² in an instant.

But at the same time, we must maintain a unified style, which is what we often call consistent style.

For example, how high should the input box be, how to display error prompts, font size and color...etc.

This is easy to do. We write the style class into a public style file form.wxss, and then import it when needed, or even import it globally.

// form.wxss
.form {
 display: block;
 font-size: 28rpx;
 position: relative;
}
.form-line {
 background-color: #fff;
 border-bottom: 1px solid #e5e5e5;
 font-size: 34rpx;
 height: 96rpx;
 line-height: 96rpx;
 display: flex;
 padding: 0 31rpx;
}
.form-title {
 box-sizing: border-box;
 background-color: #efefef;
 color: #838383;
 font-size: 28rpx;
 padding: 31rpx;
 min-height: 90rpx;
}
...
Copy after login

When we use it, we only need to add the corresponding style to the corresponding element. For example:

// xxx.wxml
<form class="form">
 <view class="form-title">请输入手机号</view>
 <view class="form-line">
  <label class="label">手机</label>
  <view class="form-control">
   <input class="f-1 va-m input" />
  </view>
 </view>
 ...
</form>
Copy after login

Then we only have two problems left between verification rules and component associations.

The ideal state of verification rules is extensible and configurable.

Scalable. As your business grows, you can add new verification rules without modifying existing rules.

Configurable. Different single or multiple validation rules can be configured individually for each form component.

How to make it definable? Just use a unified form. For example:

/*
统一的格式:
[规则名]: {
 rule: [校验方式]
 msg: [错误信息]
}
*/
const validators = {
 // 简单的校验用正则
 required: {
  rule: /.+/,
  msg: &#39;必填项不能为空&#39;
 },
 // 复杂的校验用函数
 same: {
  rule (val=&#39;&#39;, sVal=&#39;&#39;) {
   return val===this.data[sVal]
  },
  msg: &#39;密码不一致&#39;
 }
 ...
}
Copy after login

How to make it configurable? The configuration supports an array-like form, and then uses a unified function to read these verification rules in sequence and verify them one by one.

The configured rules must be on the native form component, and the value of the component can only be obtained through the event object.

If you directly bind the event for verification, it will prevent the parent page from obtaining the value, so it is best to pass the value by the parent page binding event, and pass in the event object and execution environment for processing:

/*
校验函数部分代码
e 事件对象
context 页面对象函数执行的上下文环境
*/
let validate = (e, context) => {
 // 从事件对象中获取组件的值
 let value = (e.detail.value || &#39;&#39;).trim()
 // 从事件中获取校验规则名称
 let validator = e.currentTarget.dataset.validator ? e.currentTarget.dataset.validator .split(&#39;,&#39;) : []
 // 遍历规则进行校验
 for (let i = 0; i < validator.length; i++) {
  let ruleName = validator[i].split(&#39;=&#39;)[0]
  let ruleValue = validator[i].split(&#39;=&#39;)[1]
  let rule = validators[ruleName].rule || /.*/
  if (&#39;function&#39; === typeof rule) {
   rule.call(context, value, ruleValue) ? &#39;&#39; : validators[ruleName].msg
  } else {
   rule.test(value) ? &#39;&#39; : validators[ruleName].msg
  }
 }
 ...
}
Copy after login

It is also very simple to call. Add the corresponding style according to the fixed format, configure the verification rules, and then call the verification function.


// 部分代码示例
// page.wxml
<form>
 <!-- 一个表单组件 -->
 <view class="form-line">
  <label class="label">授权手机</label>
  <view class="form-control">
   <!-- 校验规则:必须填写,且为电话号码 -->
   <input maxlength="11" class="f-1 va-m input" bindblur="validate" type="number" data-name="phone" data-validator="required,phone" confirm-type="next" value="{{phone}}" />
   <!-- 错误图标 -->
   <icon wx:if="{{form.phone!==undefined}}" type="{{form.phone?&#39;warn&#39;:&#39;success&#39;}}" size="16" />
  </view>
 </view>
 ...
</form>
// page.js
valid(e) {
 this.setData({
  [e.currentTarget.dataset.name]: e.detail.value
 })
 validate(e, this)
}
Copy after login

Summary

The above is the detailed content of Example of implementation of form verification function in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template