Textbox Validation In Client Side With ASP.NET MVC

In this article, we are going to see about how to validate Razor controls in jQuery.

Introduction

This article explains how to do the client side validation in jQuery for MVC controls. 

Knowledge required 
  1. Basic knowledge of jQuery. 
  2. Basic knowledge of ASP.NET MVC. 
Requirements
  1. Visual Studio 2010 or high.
Article Flows
  1. Create MVC Application.
  2. Create Razor cotrols in View.
  3.  Write jQuery validation in the script.
Step 1
 
(Create MVC Application)

Create new project and select ASP.NET Web Application. Click OK.

 

Select empty MVC Application to proceed.

 

After creating an empty project, create an empty controller under controller folder by right clicking controller folder.

 

Give the contoller name as JqueryValidation.



After the creation of Controller, right click Action method and click Add view to create View (the action method name will be an index).
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. namespace WebApplication1.Controllers {  
  7.     public class JqueryValidationController: Controller {  
  8.         // GET: JqueryValidation  
  9.         public ActionResult Index() {  
  10.             return View();  
  11.         }  
  12.     }  
  13. }  
Update RouteConfig 

Update routeconfig to set Index an actionmethod as homepage. In the code given below, just specify your Controllername in your Contoller and specify an actionmethod name in an action.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace WebApplication1 {  
  8.     public class RouteConfig {  
  9.         public static void RegisterRoutes(RouteCollection routes) {  
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  11.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  12.                 controller = "JqueryValidation", action = "Index", id = UrlParameter.Optional  
  13.             });  
  14.         }  
  15.     }  
  16. }  
Step 1 (Textbox validations)

First add one textbox and buttons in View
  1. @Html.TextBox("Validatetextbox"nullnew {  
  2.     @class = "form-control", @id = "Validatetextbox"  
  3. }) < br / > < button type = "button"  
  4. class = "btn btn-primary"  
  5. id = "SubmitProject" > Validate < /button>  
  6. Then add Script tag < script type = "text/javascript" > < /script>  
 Refer JavaScript library to access the predefind function from JavaScript.
  1. <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>   
1.1 Check whether textbox has value or not 

For this, write the code given below in the script. In the code given below, Validatetextbox represents the Id of the respective textbox.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $("#SubmitProject").click(function() {  
  4.             if ($("#Validatetextbox").val() == "") {  
  5.                 alert("There is no value in textbox");  
  6.             }  
  7.         });  
  8.     });  
  9. </script>  
Now, run the Application and leave textbox as empty and click Validate button. Now, you will see the screen given below.



1.2.Check whether given input is string or not?
 

There has a predefined function called isNaN to check whether the given input is a number or not and write bold content given below to check. 
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $("#SubmitProject").click(function() {  
  4.             if ($("#Validatetextbox").val() == "") {  
  5.                 alert("There is no value in textbox");  
  6.             } else {  
  7.                 if (!isNaN($("#Validatetextbox").val())) {  
  8.                     alert("Given input is number");  
  9.                 } else {  
  10.                     alert("Given input not a number");  
  11.                 }  
  12.             }  
  13.         });  
  14.     });  
  15. </script>   
Now, run the Application and see the output by giving the number and the string.

  
1.3.Get the length of textbox input

To get the length of textbox input, we have to use the predefined function, which is called length. Add the code given below in the script. 
  1. alert("The length of given input is:" + $("#Validatetextbox").val().length);  
Now, run your Application and give some input in textbox. Click Validate button to get the length of textbox input.

 

1.4.Email Validation

Here, we may use RegEx to validate the input whether that is a valid E-mail or not.
  1. validateEmail($("#Validatetextbox").val());  
  2.   
  3. function validateEmail(emailField) {  
  4.     var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;  
  5.     if (reg.test(emailField) == false) {  
  6.         alert('Invalid Email Address');  
  7.         return false;  
  8.     }  
  9.     return true;  
  10. }  
 
 
1.5.Change textbox input as uppercase on keyup?

Here, we are going to use the keyupevent to the respective textbox to perform uppercase functionality. Here, we have a predefined functionality called toUpperCase.
  1. $('#Validatetextbox').keyup(function() {  
  2.     $(this).val($(this).val().toUpperCase());  
  3. });  

1.6.Change textbox input as lowercase on keydown?

Here, we are going to use the keydown event to the respective textbox to perform lowercase functionality. Here we have a predefined functionality called toLowerCase.
  1. $('#Validatetextbox').keydown(function () {  
  2.    $(this).val($(this).val().toLowerCase());  
  3. });  

Here, we may use both toLowerCase and toLocaleLowerCase to convert the text to lowercase. There is not much difference here. Most of the time, it provides the same result but the only difference is given below.

 toLowercase toLocaleLowerCase
According to the host's current locale. The locale is based on the language settings of the Browser.
 
Generally, this method returns the same result as toLowerCase() method. However, for some locales, where language conflicts with the regular, Unicode case mappings occurs (such as Turkish), the results may vary. It is the same for uppercase

1.7 First Character uppercase in given string from textbox?

Here, we going to use the split,charAt and touppercase functionality to achieve this. 
split-> It's used to split the string or character.
charAt-> Get specific character.
touppercase-> It is required to change the text into uppercase text.
  1. var str = $('#Validatetextbox').val();  
  2. var spart = str.split(" ");  
  3. for (var i = 0; i < spart.length; i++) {  
  4.     var j = spart[i].charAt(0).toUpperCase();  
  5.     spart[i] = j + spart[i].substr(1);  
  6. }  
  7. $('#Validatetextbox').val(spart.join(" "));   
Description

var str = $('#Validatetextbox').val(); -------->Just assigning an input to str variable
var spart = str.split(" ")-------------------------->Spliting the string by space and the splitied character's is stored as an array format in spart variable
spart.length -------------------------------------->To find the length of the array(or we can say as count of character's).
for (var i = 0; i < spart.length; i++) ---------->To increameant the position
spart[i].charAt(0).toUpperCase();------------->Here, we are only changing the first letter as an uppercase character (you may check by changing the charAt(position),
substr(1)-------------------------------------------->substr is an opposite of remove.
$('#Validatetextbox').val(spart.join(" "))-------->Finally, we are merging all characters and assigning that value to textbox.
 
I hope you enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.