Asynchronous JavaScript And XML (Ajax) is the cornerstone of communication between your client-side and server-side code. Regardless of whether you use JavaScript, jQuery, Angular, React or any other client-side language, they all use Ajax under the hood to send and receive data from a web server. Using Ajax you can read data from, or send data to, a web server all without reloading the current web page. In other words, you can manipulate the DOM and the data for the web page without having to perform a post-back to the web server that hosts the web page. Ajax gives you a huge speed benefit because there is less data going back and forth across the internet. Once you learn how to interact with Ajax, you will find the concepts apply to whatever front-end language you use. In this article you are going to learn to validate data using the jQuery plugin.
Download Starting Projects
Instead of creating a front-end web server and a .NET Core Web API server in this article I have two sample projects you may download to get started quickly. If you are unfamiliar with building a front-end web server and a .NET Core Web API server, you can build them from scratch step-by-step in my three blog posts listed below.
- Create CRUD Web API in .NET Core
- Create .NET Core MVC Application for Ajax Communication
- Create Node Web Server for Ajax Communication
You can find all three of these blog posts at https://www.pdsa.com/blog. Instructions for getting the samples that you can start with are contained in each blog post. You are going to need blog post #1, then choose the appropriate web server you wish to use for serving web pages; either .NET MVC (#2) or NodeJS (#3).
Start Both Projects
After you have reviewed the blog posts and downloaded the appropriate sample projects to your hard drive, start both projects running. The first project to load is the Web API project. Open the WebAPI folder in VS Code and click on the Run | Start Debugging menus to load and run the .NET Web API project.
Open the AjaxSample folder in VS Code.
If you are using node, open the AjaxSample folder in VS Code, open a Terminal window and type npm install. Then type npm run dev to start the web server running and to have it display the index page in your browser.
If you are using the .NET MVC application, open the AjaxSample-NET folder in VS Code and click on the Run | Start Debugging menus to load and run the .NET MVC project. The index.cshtml page should now be displayed in your browser window.
Try it Out
Go to your browser for the front-end web server (localhost:3000) and you should see a page that looks like Figure 1. If your browser looks like this, everything is working for your front-end web server.
Open the Browser Tools in your browser, usually accomplished by clicking the F12 key. Click the Get Products button and you should see the product data retrieved from the Product table in the AdventureWorksLT database and displayed in your console window.
Install jQuery
If you have not already done so, you need to install jQuery into your node server project. If you are using the MVC application, jQuery is already installed, so you can skip to the next section of this article. Open the Terminal window in VS Code in your node server project and type the following command.
npm install jquery
After jQuery has been installed, open you index page and add a new <script> tag to use jQuery before all other <script> tags on the page.
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
Add jQuery Validation Plugin
You need to add the jQuery validation plug to the AjaxSample project. In the terminal window, type the following command.
npm i jquery-validation
Open the index page, and immediately after the <script> tag for jQuery, add a new <script> tag for jQuery validation. It is important that the <script> tag for the jQuery library is listed before any other jQuery plugins.
<script src="/node_modules/jquery/dist/jquery.min.js"></script> <script src="/node_modules/jquery-validation /dist/jquery.validate.min.js"> </script>
Add Additional Attributes for Validation
The jQuery validation plugin is an extension to the jQuery library to help you perform rich, client-side validation of data. To provide the help the validation library needs, you need to add some attributes to each input you wish to validate. For example, you can use all the typical HTML attributes such as required, minlength, maxlength, min, max, type and pattern. jQuery validation also goes beyond these HTML attributes and supplies methods and extensions to help you validate email, url, date, numeric, credit cards, phones and more. For more information on jQuery validation, visit the documentation at https://jqueryvalidation.org/documentation.
Replace the <input> elements with the code shown in bold in Listing 1 to the index page. Besides the validation attributes, you also add the title attribute as this is used by jQuery validation to display an error message for required fields.
<form> <div class="row"> <label for="productID">Product ID</label> <input id="productID" name="productID" type="text" value="0" /> </div> <div class="row"> <label for="name">Product Name</label> <input id="name" name="name" type="text" title=" Product Name is required" required minlength="4" /> </div> <div class="row"> <label for="productNumber">Product Number</label> <input id="productNumber" name="productNumber" type="text" title=" Product Number is required" required minlength="3" /> </div> <div class="row"> <label for="color">Color</label> <input id="color" name="color" type="text" title=" Color is required" required minlength="3" /> </div> <div class="row"> <label for="standardCost">Cost</label> <input id="standardCost" name="standardCost" type="number" required min="0.01" /> </div> <div class="row"> <label for="listPrice">Price</label> <input id="listPrice" name="listPrice" type="number" required min="0.02" /> </div> <div class="row"> <label for="sellStartDate">Sell Start Date</label> <input id="sellStartDate" name="sellStartDate" type="text" required min="2010-01-01" /> </div> <div class="row"> <label id="message" class="infoMessage"></label> <label id="error" class="errorMessage"></label> </div> <div class="row"> <button type="button" onclick="get();"> Get Products </button> <button type="button" onclick="getProduct();"> Get a Product </button> <button data-type="post">Insert Product</button> <button data-type="put">Update Product</button> <button type="button" onclick="deleteProduct();"> Delete Product </button> </div> </form>
Validate Data
Within the <script> tag in the index page, add the code shown in Listing 2. The validate() method applied to the form selector checks all fields to see if they are all valid. If they are not, the appropriate error messages appear. If they are correct, the valid() method returns a true, which then allows the form to be submitted to the Web API.
$(document).ready(function () { // Validate the form using the the various attributes $("form").validate(); // Submit the form $("form").submit(function (event) { event.preventDefault(); // Ensure the form has been validated if ($("form").valid()) { if ($(document.activeElement).data("type") == "post") { insertProduct(); } else { updateProduct(); } } }); });
Try it Out
Save the changes to the index page and go to your browser. Click on the Insert Product button and you should see the message in the title attribute appear next to the fields in error as shown in Figure 2.
Using jQuery Rules
While the above sample was simple to implement, what if you want some more control over what can be input into a field, or what error message is displayed? The validate() method accepts an options object into which you can set a rules property that contains a set of rules for each input field. Within the rules property, create a property that is the same as the name attribute on one of your input elements on your page you wish to apply rules to. The value for the property is a literal object into which you may add as many rules as you want such as required, minlength, min, max, creditcard, number, etc. Modify the code in the $(document).ready() method with the code shown in Listing 3.
$(document).ready(function () { $("form").validate({ rules: { name: { required: true, minlength: 4 }, productNumber: { required: true, minlength: 3 }, color: { required: true, minlength: 3 }, standardCost: { required: true, number: true, min : 0.01 }, listPrice: { required: true, number: true, min : 0.02 }, sellStartDate: { required: true, date: true } }, messages: { name: { required: " Please enter a product name", minlength: " The name must be at least 4 characters long" }, productNumber: { required: " Please enter a product number", minlength: " The product number must be at least 3 characters long" }, color: { required: " Please enter a product color", minlength: " The color must be at least 3 characters long" }, standardCost: { required: " Please enter a cost", min: "Enter a value greater than $0.01" }, listPrice: { required: " Please enter a price", min: "Enter a value greater than $0.02" }, sellStartDate: { required: " Please enter a sell start date" } }, submitHandler: function (form) { if ($(document.activeElement).data("type") == "post") { insertProduct(); } else { updateProduct(); } } }); });
Try it Out
Save the changes to the index page and go to your browser. Enter two characters into the Product Name field, and a -1 into the Cost or Price field and click on the Insert Product button. You should now see the error messages from the options object instead of the default ones from jQuery validation.
Summary
There are many more options you can take advantage of in jQuery validation. Check out the jQuery validation documentation at https://jqueryvalidation.org/documentation for the complete list of options and examples you can look at. You should definitely take advantage of this great client-side validation library in your web pages. Client-side validation makes your application more responsive, which your users will appreciate.
#jquery #ajax #javascript #validation #pauldsheriff #development #programming