Table of Contents
1.school.wxml:
2.school.js:
Home WeChat Applet Mini Program Development Development of small programs: form verification (code)

Development of small programs: form verification (code)

Aug 10, 2018 pm 03:55 PM
Applets form validation

The content of this article is about the development of small programs: form verification (code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1.school.wxml:

<form bindsubmit=&#39;formSubmit&#39;><view class="subInfo">
  <view class="subInfoItem clearfix">
    <text class="tag need">校区名称</text>
    <input name=&#39;name&#39; value=&#39;&#39; placeholder=&#39;请输入校区名称&#39; placeholder-class=&#39;placeholder&#39;></input>
  </view>
  <view class="subInfoItem clearfix">
    <text class="tag">联系电话</text>
    <input name=&#39;contactphone&#39; value=&#39;&#39; placeholder=&#39;请输入联系电话&#39; placeholder-class=&#39;placeholder&#39;></input>
  </view></view><view class=&#39;btnWrap&#39;>
  <button class=&#39;saveBtn&#39; form-type=&#39;submit&#39;>保存</button></view></form>
Copy after login

2.school.js:

import WxValidate from &#39;../utils/classes/WxValidate.js&#39;var validate;

Page({    // 初始化表单校验
    initValidate(){        // 创建实例对象
        this.validate = new WxValidate({
            name: {
                required: true,
                maxlength: 20
            },
            contactphone: {
                tel: true
            }
        }, {
                name: {
                    required: &#39;请输入校区名称!&#39;,
                    maxlength: &#39;名称不得超过20字!&#39;
                },
                contactphone: {
                    tel: &#39;电话格式不正确!&#39;
                }
            })
    },
    data: {

    },
    onLoad: function (options) {
        this.initValidate()
    },
    formSubmit(e){        // 校验表单
        if (!this.validate.checkForm(e.detail.value)){            
        const error = this.validate.errorList[0];
            wx.showToast({
                title: `${error.msg} `,
                icon: &#39;none&#39;
            })            
            return false
        }        // 保存操作...
    }
})
Copy after login

Note:

WxValidate - Form Validation

Plug-in introduction

This plug-in is packaged with reference to jQuery Validate. It provides a set of commonly used validation rules for mini program forms, including mobile phone number, email verification, etc., and also provides the ability to add custom validation Validation method to make form validation easier.

Parameter Description

ParameterTypeDescription
rulesobjectRules for validating fields
messagesobjectPrompt information for verification fields

Built-in verification rules

Serial numberRuleDescription
1required: true This is a required field.
2email: truePlease enter a valid email address.
3tel: truePlease enter your 11-digit mobile phone number.
4url: truePlease enter a valid URL.
5date: truePlease enter a valid date.
6dateISO: truePlease enter a valid date (ISO), for example: 2009-06-23 , 1998/01/22.
7number: truePlease enter a valid number.
8digits: trueOnly numbers can be entered.
9idcard: truePlease enter your 18-digit valid ID card.
10equalTo: 'field'The input value must be the same as field.
11contains: 'ABC'The input value must contain ABC.
12minlength: 5You must enter at least 5 characters.
13maxlength: 10You can enter up to 10 characters.
14rangelength: [5, 10]Please enter a length of characters between 5 and 10.
15min: 5Please enter a value not less than 5.
16max: 10Please enter a value no greater than 10.
17range: [5, 10]Please enter a value between 5 and 10.

Common instance methods

NameReturn typeDescription
checkForm(e)boolean Verify the rules of all fields and return whether the verification is passed .
valid()booleanReturns whether the verification is passed.
size()number Returns the number of error messages.
validationErrors()array Returns all error messages.
addMethod(name, method, message)booleanAdd a custom verification method.

addMethod(name, method, message) - Add custom verification

The first parameter name is the name of the added method. The second parameter method is a function that receives three parameters (value, param), value is the value of the element, and param is the parameter. The third parameter message is a custom error message.

Instructions for use

// 验证字段的规则const rules = {
    email: {
        required: true,
        email: true,
    },
    tel: {
        required: true,
        tel: true,
    },
    idcard: {
        required: true,
        idcard: true,
    },
}// 验证字段的提示信息,若不传则调用默认的信息const messages = {
    email: {
        required: &#39;请输入邮箱&#39;,
        email: &#39;请输入正确的邮箱&#39;,
    },
    tel: {
        required: &#39;请输入手机号&#39;,
        tel: &#39;请输入正确的手机号&#39;,
    },
    idcard: {
        required: &#39;请输入身份证号码&#39;,
        idcard: &#39;请输入正确的身份证号码&#39;,
    },
}
// 创建实例对象
this.WxValidate = new WxValidate(rules, messages)
// 自定义验证规则
this.WxValidate.addMethod(&#39;assistance&#39;, (value, param) => {    
return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
}, &#39;请勾选1-2个敲码助手&#39;)// 如果有个表单字段的 assistance,则在 rules 中写assistance: {
    required: true,
    assistance: true,
},// 调用验证方法,传入参数 e 是 form 表单组件中的数据submitForm(e) {    
const params = e.detail.value

    console.log(params)    // 传入表单数据,调用验证方法
    if (!this.WxValidate.checkForm(e)) {        
    const error = this.WxValidate.errorList[0]        
    return false
    }
},
Copy after login

Related recommendations:

Mini Program: Code to implement click countdown

Mini program component: Introduction to the chat session component (with code)

Implementation of interaction between the mini program and the background (with code)

The above is the detailed content of Development of small programs: form verification (code). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to use vue and Element-plus to implement step-by-step forms and form verification How to use vue and Element-plus to implement step-by-step forms and form verification Jul 17, 2023 pm 10:43 PM

How to use Vue and ElementPlus to implement step-by-step forms and form verification. In web development, forms are one of the most common user interaction components. For complex forms, we often need to perform step-by-step filling and form verification functions. This article will introduce how to use Vue and ElementPlus framework to achieve these two functions. 1. Step-by-step form A step-by-step form refers to dividing a large form into several small steps, and users need to fill in the steps according to the steps. We can take advantage of Vue’s componentization and routing

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

Can small programs use react? Can small programs use react? Dec 29, 2022 am 11:06 AM

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Tutorial on writing a simple chat program in Python Tutorial on writing a simple chat program in Python May 08, 2023 pm 06:37 PM

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Teach you how to use public account template messages in mini programs (with detailed ideas) Teach you how to use public account template messages in mini programs (with detailed ideas) Nov 04, 2022 pm 04:53 PM

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

See all articles