Home > CMS Tutorial > WordPress > body text

Simplify form validation with jQuery

王林
Release: 2023-09-03 18:33:01
Original
1433 people have browsed it

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>
Copy after login

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>
Copy after login

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();
});
Copy after login

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
}
}
});
});
Copy after login

在上面的代码片段中,键 nameageemailweight 只是名称输入元素。每个键都有一个对象作为其值,对象中的键值对决定如何验证输入字段。

这些验证选项与您可以在表单标记中添加的属性类似。例如,将 required 设置为 true 将使该元素成为表单提交所需的元素。将 minlength 设置为 3 之类的值将强制用户在文本输入中输入至少 3 个字符。还有一些其他内置验证方法,文档页面上对此进行了简要描述。

在上述代码中需要注意的一件事是,如果年龄超过 50 岁,则使用 depends 有条件地将体重设为必填字段。这是通过返回 age 输入字段中输入的值超过 50,则在回调函数中返回 true。

创建您自己的错误消息

此插件还允许您为表单中的不同验证规则设置错误消息。首先,将 messages 键的值设置为一个对象,该对象包含输入字段的键值对和相应的错误消息。

下面是一个示例,它将显示每个输入字段的自定义错误消息。

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"
}
}
Copy after login

就像规则一样,messages 依赖于输入字段的名称。每个输入字段都将接受一个具有键值对的对象作为其值。每种情况的关键是必须遵循的验证规则。该值只是您想要在违反特定规则时显示的错误消息。

例如,如果 age 输入字段留空,将触发 required 错误消息。但是,如果您在输入字段中输入除数字之外的任何其他内容,则会触发 number 错误。

您会注意到的一件事是,如果您未提供自定义错误消息,该插件将显示验证规则的通用错误消息。尝试在以下演示中填写不同的值,您将看到自定义和通用错误消息按预期显示。

自定义错误消息的外观

有时,您可能希望将自己的类添加到有效和无效输入中,以便更具体地定位它们或更好地与现有主题集成。

您可以使用 errorClassvalidClass 键更改添加到有效或无效输入元素的类。这可以帮助防止由于重复使用相同的类名而导致一些不必要的冲突。默认情况下, error 类被分配给每个无效的输入元素和标签。 valid 类被分配给每个有效的输入元素。

请务必记住,将 errorClass 设置为 fail-alert 将从无效元素中删除 error 类。您必须使用 errorClass: "error failure-alert" 将多个类分配给同一元素。 validClass 也是如此。

当用户输入有效的内容时,不会向表单添加任何其他标签。因此,来自 validClass 的类被分配给有效的输入元素。

以下代码片段基于前面的示例,向无效和有效元素添加自定义 CSS 类和样式。

唯一的附加 JavaScript 代码用于分配类。

$(document).ready(function() {
$("#basic-form").validate({
errorClass: "error fail-alert",
validClass: "valid success-alert",
// ... More validation code from previous example
Copy after login

这是我们将用来更改错误消息外观的 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;
}
Copy after login

除了自定义错误消息之外,我们还向有效的输入元素添加我们自己的样式。这是一个 CodePen 演示,向我们展示最终结果。

更改插件行为的更多选项

您可以通过设置 onfocusoutonkeyuponclickfalse。请记住,布尔 true 不是这些键的有效值。这基本上意味着,如果您希望插件验证或失去对按键事件的关注,只需保持这些选项不变即可。

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

使用 jQuery 简化表单验证

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

使用 jQuery 简化表单验证

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

使用 jQuery 简化表单验证

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!