In the previous tutorial, we discussed how to implement basic form validation using some input attributes and some regular expressions in HTML5.
In this tutorial, you will learn how to add simple form validation to your website using the jQuery plugin.
There are many uses for validating forms using the jQuery plugin. It gives you extra features like easily displaying custom error messages and adding conditional logic to jQuery form validation. Validation libraries also help you add validation to HTML forms with minimal or no changes to the markup. Validity conditions can also be easily added, removed or modified at any time.
start using
We will be using the jQuery validation plugin in this tutorial. The plugin provides a lot of functionality and also helps you define your own validation logic.
Before we start using the plugin in our realm, we must include the necessary files in our project. There are two different files to include. The first is the core file, which contains the core functionality of the plugin, including everything from different validation methods to some custom selectors. The second file contains additional methods for validating inputs such as credit card numbers and US phone numbers.
You can add these files to your project through a package manager such as Bower or NPM. You can also directly get the CDN links to your files and add them to the script
tags on your web pages. Since this is a jQuery based plugin, you will also need to add a link to the jQuery library.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
After adding these files, you can start validating any form using the validate
method.
Validate your first form
You can start using this plugin without making any major changes to your markup. The only thing you might need to change is to add id
or class
to the form you want to validate if you don't already have one.
This is the markup for a basic form, which we will validate using the jQuery validation plugin.
<form id="basic-form" action="" method="post"> <p> <label for="name">Name <span>(required, at least 3 characters)</span></label> <input id="name" name="name" minlength="3" type="text" required> </p> <p> <label for="email">E-Mail <span>(required)</span></label> <input id="email" type="email" name="email" required> </p> <p> <input class="submit" type="submit" value="SUBMIT"> </p> </form>
The attributes we use are the same as those used in the previous HTML5 based form validation tutorial. The form will still validate without us adding any JavaScript. However, using the plugin for validation will allow us to display an error message right below the invalid input field. We can also style the errors if needed.
To start using this plugin to validate forms, just add the following JavaScript code to your webpage:
$(document).ready(function() { $("#basic-form").validate(); });
This is based on the assumption that you have already added the required JavaScript files. Adding these JavaScript lines will ensure that your form is properly validated and any error messages are displayed. This is a working demo.
The library only displays error messages when necessary, making it as user-friendly as possible. For example, if you tab through the name and email fields without actually entering any information, you won't get any error messages. However, if you try to move to the email field after entering only one character in the name field, you will receive an error message about entering at least three characters.
Use the label
element to inject error messages into the DOM. They all have a error
class, so it's easy to apply your own styles, like we did in the example. The same goes for invalid input, a error
class is also added.
validate()
Method options
In the previous example, we just called the validate()
method without passing it any options. However, we can also pass an object to this method along with a number of options within that object. The values ??of these options will determine how the form plugin handles validation, errors, etc.
If you want this plugin to ignore certain elements during validation, you can easily do this by passing a class or selector to ignore()
. When the plugin validates input, it ignores all form elements with that specific selector.
Add validation rules for input fields
You can also pass some rules to the validate()
method to determine how to validate the input value. rules
The value of the parameter should be an object with key-value pairs. The key in each case is the name of the element we want to validate. The value of this key is an object containing a set of rules that will be used for validation.
You can also add conditional logic to the different fields you want to validate using the depends
keyword and pass it a callback function that returns true
or false
. Here's an example of using simple rules to define how input is validated.
$(document).ready(function() { $("#basic-form").validate({ rules: { name : { required: true, minlength: 3 }, age: { required: true, number: true, min: 18 }, email: { required: true, email: true }, weight: { required: { depends: function(elem) { return $("#age").val() > 50 } }, number: true, min: 0 } } }); });
在上面的代碼片段中,鍵 name
、age
、email
和 weight
只是名稱輸入元素。每個鍵都有一個對象作為其值,對象中的鍵值對決定如何驗證輸入字段。
這些驗證選項與您可以在表單標(biāo)記中添加的屬性類似。例如,將 required
設(shè)置為 true 將使該元素成為表單提交所需的元素。將 minlength
設(shè)置為 3 之類的值將強制用戶在文本輸入中輸入至少 3 個字符。還有一些其他內(nèi)置驗證方法,文檔頁面上對此進行了簡要描述。
在上述代碼中需要注意的一件事是,如果年齡超過 50 歲,則使用 depends
有條件地將體重設(shè)為必填字段。這是通過返回 age
輸入字段中輸入的值超過 50,則在回調(diào)函數(shù)中返回 true。
創(chuàng)建您自己的錯誤消息
此插件還允許您為表單中的不同驗證規(guī)則設(shè)置錯誤消息。首先,將 messages
鍵的值設(shè)置為一個對象,該對象包含輸入字段的鍵值對和相應(yīng)的錯誤消息。
下面是一個示例,它將顯示每個輸入字段的自定義錯誤消息。
messages : { name: { minlength: "Name should be at least 3 characters" }, age: { required: "Please enter your age", number: "Please enter your age as a numerical value", min: "You must be at least 18 years old" }, email: { email: "The email should be in the format: abc@domain.tld" }, weight: { required: "People with age over 50 have to enter their weight", number: "Please enter your weight as a numerical value" } }
就像規(guī)則一樣,messages
依賴于輸入字段的名稱。每個輸入字段都將接受一個具有鍵值對的對象作為其值。每種情況的關(guān)鍵是必須遵循的驗證規(guī)則。該值只是您想要在違反特定規(guī)則時顯示的錯誤消息。
例如,如果 age
輸入字段留空,將觸發(fā) required
錯誤消息。但是,如果您在輸入字段中輸入除數(shù)字之外的任何其他內(nèi)容,則會觸發(fā) number
錯誤。
您會注意到的一件事是,如果您未提供自定義錯誤消息,該插件將顯示驗證規(guī)則的通用錯誤消息。嘗試在以下演示中填寫不同的值,您將看到自定義和通用錯誤消息按預(yù)期顯示。
自定義錯誤消息的外觀
有時,您可能希望將自己的類添加到有效和無效輸入中,以便更具體地定位它們或更好地與現(xiàn)有主題集成。
您可以使用 errorClass
和 validClass
鍵更改添加到有效或無效輸入元素的類。這可以幫助防止由于重復(fù)使用相同的類名而導(dǎo)致一些不必要的沖突。默認(rèn)情況下, error
類被分配給每個無效的輸入元素和標(biāo)簽。 valid
類被分配給每個有效的輸入元素。
請務(wù)必記住,將 errorClass
設(shè)置為 fail-alert
將從無效元素中刪除 error
類。您必須使用 errorClass: "error failure-alert"
將多個類分配給同一元素。 validClass
也是如此。
當(dāng)用戶輸入有效的內(nèi)容時,不會向表單添加任何其他標(biāo)簽。因此,來自 validClass
的類被分配給有效的輸入元素。
以下代碼片段基于前面的示例,向無效和有效元素添加自定義 CSS 類和樣式。
唯一的附加 JavaScript 代碼用于分配類。
$(document).ready(function() { $("#basic-form").validate({ errorClass: "error fail-alert", validClass: "valid success-alert", // ... More validation code from previous example
這是我們將用來更改錯誤消息外觀的 CSS:
label.error.fail-alert { border: 2px solid red; border-radius: 4px; line-height: 1; padding: 2px 0 6px 6px; background: #ffe6eb; } input.valid.success-alert { border: 2px solid #4CAF50; color: green; }
除了自定義錯誤消息之外,我們還向有效的輸入元素添加我們自己的樣式。這是一個 CodePen 演示,向我們展示最終結(jié)果。
更改插件行為的更多選項
您可以通過設(shè)置 onfocusout
、onkeyup
或 onclick
到 false
。請記住,布爾 true 不是這些鍵的有效值。這基本上意味著,如果您希望插件驗證或失去對按鍵事件的關(guān)注,只需保持這些選項不變即可。
You can also choose to change the element where the error occurred. By default, the plugin displays all error messages using the label
element, but you can change it to em
or any other element key using errorElement
. The error element itself can then be wrapped in another HTML element using the wrapper
key.
These are some of the most common options you might use when validating a form. However, if you want to change the location of error messages or group them together, there are some other validation options that may come in handy.
jQuery Form Validation, JavaScript and jQuery Forms on CodeCanyon
Learning how to do simple form validation yourself is a great skill. But you can get a deeper understanding by downloading these helpful jQuery and JavaScript forms from CodeCanyon:
1. jQuery Step Wizard with Step Form Builder: Timon Step Form
If you want to build multi-step forms, Timon Step Form download is perfect for you. It features a variety of form elements and transition effects that you can use to customize your work. Timon also has a drag-and-drop builder, which means you can build forms without any coding knowledge. It also has jQuery form validation.
2. Just advanced form
Reading the title of this purchase will let you know exactly what you are getting here. But there's more to these forms than meets the eye. More than 110 forms are included to use, or you can use the framework to make a unique form for yourself.
3. sky form
We round out our list with highly customizable sky shapes. It features modern elements and a variety of color schemes. Six states are also designed, including hover, focus, etc. In addition to these features and cross-browser compatibility, there are over 300 vector icons in Sky Forms.
Final Thoughts
In this tutorial, we learned how to take form validation to the next level using the jQuery plugin. Using simple JavaScript form validation gives us more control over basic HTML validation. For example, you can easily control how and when different error messages are displayed when an input is populated with invalid values.
Similarly, you can also specify whether the plugin should skip validation of certain specific elements. I highly recommend you read the documentation for this plugin and some best practices on how to use it properly.
In our next tutorial, you'll learn about more JavaScript-based tools and plugins to help you easily create and validate forms.
While you're here, check out some of our other posts about JavaScript forms and form validation!
The above is the detailed content of Simplify form validation with jQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.
