jQuery implements form validation

jQuery implements form validation

Use jQuery to implement form validation, for your reference, the specific contents are as follows

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
    <!--Import jQuery-->
    <script src="js/jquery-3.3.1.js"></script>
    <!--Perform form validation-->
    <script>
        /*
    Form validation:
     1. Username: single word characters, length 8 to 20 characters 2. Password: single word characters, length 8 to 20 characters 3. Email: email format 4. Name: not empty 5. Mobile phone number: mobile phone number format 6. Date of birth: not empty*/
 
        // Check username // Word characters, length 8 to 20 characters function checkUsername() {
            // 1. Get the username value var username = $("#username").val();
            // 2. Define validation regular expression var reg_username = /^\w{8,20}$/;
            // 3. Determine whether the verification requirements are met and give a prompt message var flag = reg_username.test(username);
            if (flag) {
                // Legal username$("#username").css("border", "");
            } else {
                // Username is illegal, add a red border $("#username").css("border", "1px solid red");
            }
            // 4. Return whether the verification is passed return flag;
        }
 
        // Verify password function checkPassword() {
            //1. Get the password value var password = $("#password").val();
            //2. Define regular expression var reg_password = /^\w{8,20}$/;
            //3. Judge and give prompt information var flag = reg_password.test(password);
            if (flag) {
                //The password is legal$("#password").css("border", "");
            } else {
                //The password is illegal, add a red border $("#password").css("border", "1px solid red");
            }
            // 4. Return to check whether it passes the return flag;
        }
 
        // Check email function checkEmail() {
            //1. Get the mailbox var email = $("#email").val();
            //2. Define regular [email protected]
            var reg_email = /^\w+@\w+\.\w+$/;
            //3. Judge var flag = reg_email.test(email);
            if (flag) {
                $("#email").css("border", "");
            } else {
                $("#email").css("border", "1px solid red");
            }
            // 4. Return to check whether it passes the return flag;
        }
 
        // Check name function checkName() {
            // 1. Get the name var name = $("#name").val();
            // 2. Check if it is not empty and return whether the check passes if (typeof name == "undefined" || name == null || name == "") {
                $("#name").css("border", "1px solid red");
                return false;
            } else {
                $("#name").css("border", "");
                return true;
            }
        }
 
        // Check phone number function checkTelephone() {
            // 1. Get the phone number var telephone = $("#telephone").val();
            // 2. Define regular expression var reg_tel = /^1(3|4|5|6|7|8|9)\d{9}$/;
            // 3. Judge var flag = reg_tel.test(telephone);
            if (flag) {
                $("#telephone").css("border", "");
            } else {
                $("#telephone").css("border", "1px solid red");
            }
            // 4. Return to check whether it passes the return flag;
        }
 
        // Check date of birth function checkBirthday() {
            // 1. Get the date of birth var birthday = $("#birthday").val();
            // 2. Check if it is not empty and return whether the verification is passed if (typeof birthday == "undefined" || birthday == null || birthday == "") {
                $("#name").css("border", "1px solid red");
                return false;
            } else {
                $("#name").css("border", "");
                return true;
            }
        }
 
        // Check $(function () {
            //When the form is submitted, all validation methods are called $("#registerForm").submit(function () {
                // If this method has no return value, or returns true, the form is submitted. If it returns false, the form is not submitted. // 1. Send data to the server if (checkUsername() && checkPassword() && checkEmail() && checkName() && checkTelephone() && checkBirthday()) {
                    // Verification passed, send ajax request, submit the form data username=zhangsan&password=123
                    $.post("registerServlet", $(this).serialize(), function (data) {
                        if (data.flag) {
                            // Registration successful, jump to the success page alert("Registration successful!");
                        } else {
                            //Registration failed, add prompt information to errorMsg$("#errorMsg").html(data.errorMsg);
                        }
                    });
                }
                //2. Do not allow the page to jump return false;
            });
            //When a component loses focus, call the corresponding check method $("#username").blur(checkUsername);
            $("#password").blur(checkPassword);
            $("#email").blur(checkEmail);
            $("#name").blur(checkName);
            $("#telephone").blur(checkTelephone);
            $("#birthday").blur(checkBirthday);
        })
    </script>
</head>
<body>
<div>
    <p>User Registration</p>
    <!--Registration form-->
    <div id="errorMsg" style="color:red;text-align: center"></div>
    <form id="registerForm" action="registerServlet" method="post">
        <table style="margin-top: 25px;">
            <tr>
                <td class="td_left">
                    <label for="username">Username</label>
                </td>
                <td class="td_right">
                    <input type="text" id="username" name="username" placeholder="Please enter your account number">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="password">Password</label>
                </td>
                <td class="td_right">
                    <input type="text" id="password" name="password" placeholder="Please enter your password">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="email">Email</label>
                </td>
                <td class="td_right">
                    <input type="text" id="email" name="email" placeholder="Please enter your email">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="name">Name</label>
                </td>
                <td class="td_right">
                    <input type="text" id="name" name="name" placeholder="Please enter your real name">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="telephone">Mobile number</label>
                </td>
                <td class="td_right">
                    <input type="text" id="telephone" name="telephone" placeholder="Please enter your phone number">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="sex">Gender</label>
                </td>
                <td class="td_right gender">
                    <input type="radio" id="sex" name="sex" value="Male" checked> Male<input type="radio" name="sex" value="Female"> Female</td>
            </tr>
            <tr>
                <td class="td_left">
                    <label for="birthday">Date of Birth</label>
                </td>
                <td class="td_right">
                    <input type="date" id="birthday" name="birthday" placeholder="year/month/day">
                </td>
            </tr>
            <tr>
                <td class="td_left">
                </td>
                <td class="td_right check">
                    <input type="submit" class="submit" value="Register">
                    <span id="msg" style="color: red;"></span>
                </td>
            </tr>
        </table>
    </form>
</div>
</body>
<script>
 
</script>
</html>

You don't need to look at the background processing code, it is only needed for the front and back ends to interact, RegisterServlet.java

package com.demo.servlet;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(key + ":" + parameterMap.get(key)[0]);
        }
// String str="{flag:true,errorMsg:'Registration failed'}";// Error example String str="{\"flag\":\"true\",\"errorMsg\":\"Registration failed\"}";
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(str);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

Effect:

Code address for this section: Demo

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Getting started with the basic usage of jquery validate.js form validation
  • Implementing Form Validation Based on Bootstrap+jQuery.validate
  • jQuery form validation using plugin formValidator
  • Jquery practice form validation implementation code
  • Using jQuery to implement form validation
  • Implementing form validation based on Jquery
  • jQuery form validation plugin formValidation implements personalized error prompts
  • jQuery implements form validation and prevents illegal submission
  • Jquery plugin easyUi form validation submission (sample code)
  • jQuery implements form validation example for user registration

<<:  Several ways to store images in MySQL database

>>:  Detailed explanation of setting resource cache in nginx

Recommend

Markup Language - Anchor

Previous: Markup Language - Phrase Elements Origin...

Example of using CASE WHEN in MySQL sorting

Preface In a previous project, the CASE WHEN sort...

Vue handwriting loading animation project

When the page is not responding, displaying the l...

Tips for adding favicon to a website: a small icon in front of the URL

The so-called favicon, which is the abbreviation o...

How to install nginx in docker and configure access via https

1. Download the latest nginx docker image $ docke...

Three principles of efficient navigation design that web designers must know

Designing navigation for a website is like laying...

Three ways to communicate between React components (simple and easy to use)

Table of contents 1. Parent-child component commu...

Vue.js application performance optimization analysis + solution

Table of contents 1. Introduction 2. Why do we ne...

Basic implementation method of cross-component binding using v-model in Vue

Hello everyone, today we will talk about how to u...

Change the MySQL database engine to InnoDB

PS: I use PHPStudy2016 here 1. Stop MySQL during ...

Vue implements online preview of PDF files (using pdf.js/iframe/embed)

Preface I am currently working on a high-quality ...

Detailed explanation of real-time backup knowledge points of MySQL database

Preface The need for real-time database backup is...

MySQL5.7.27-winx64 version win10 download and installation tutorial diagram

MySQL 5.7 installation We are learning MySQL data...

Solve the problem of using swiper plug-in in vue

Since I used this plugin when writing a demo and ...

An article to understand the usage of typeof in js

Table of contents Base Return Type String and Boo...