Validation In ASP.NET MVC Model Binding Using jQuery

jQuery Validation in model binding is used to check if the user has entered all the valid text in input fields or not. This is done before submitting the form to the server so that server-side load lifting can be minimized.

jQuery Validation in model binding is used to check if the user has entered all the valid text in input fields or not. This is done before submitting the form to the server so that server-side load lifting can be minimized.
We are using Data Annotation validators to perform the validation in an ASP.NET MVC application in model binding simply by adding one or more attributes – such as the required or StringLength attribute – to a class property.

We can also use jQuery in model binding to check if the user has entered all the valid text in input fields or not.

Step 1

Add a class with any name in Model Folder.
  1. public class Registration {  
  2.     public string FirstName {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string LastName {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public int UserId {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string Password {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Email {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public string Contact {  
  23.         get;  
  24.         set;  
  25.     }  
  26. }  
Step 2

In View model Registration.cshtml,
  1. @using (Html.BeginForm("Registration""Login", FormMethod.Post, new {onsubmit="ValidateUser();"}))  
  2. {  
  3. <div class="form-group">  
  4.    <label for="First Name" class="col-md-3 control-label">First Name</label>  
  5.     <div class="col-md-9">  
  6.       @Html.TextBoxFor(x => x.FirstName, ""new { @class = "form- control", placeholder = "First Name" })  
  7.     @Html.ValidationMessageFor(x => x.FirstName, "Please enter First Name"new { @class = "text- danger", style       = "display:none" })  
  8.    </div>  
  9. </div>  
  10. <br />  
  11. <div class="form-group">  
  12.    <label for="firstname" class="col-md-3 control-label">Last Name</label>  
  13. <div class="col-md-9">  
  14.    @Html.TextBoxFor(x => x.LastName, ""new { @class = "form-control", placeholder = "Last Name" })  
  15.    @Html.ValidationMessageFor(x => x.LastName, "Please enter Last Name"new { @class = "text-   danger", style    = "display:none" })  
  16. </div>  
  17. </div>  
  18. <br />  
  19. <div class="form-group">  
  20.    <label for="lastname" class="col-md-3 control-label">Email</label>  
  21. <div class="col-md-9">  
  22.    @Html.TextBoxFor(x => x.Email, ""new { @class = "form-control", placeholder = "Email" })  
  23.    @Html.ValidationMessageFor(x => x.Email, "Please enter Email"new { @class = "text-   danger", style = "disp   lay:none" })  
  24.    </div>  
  25. </div>  
  26. <br />  
  27. <div class="form-group">  
  28.    <label for="password" class="col-md-3 control-label">Password</label>  
  29. <div class="col-md-9">  
  30.    @Html.PasswordFor(x => x.Password, new { @class = "form-   control", placeholder = "Password", onblur = "Pass   wordStrength();" })  
  31.    @Html.ValidationMessageFor(x => x.Password, "Please enter Password"new { @class = "text-   danger", style =    "display:none" })  
  32. </div>  
  33. </div>  
  34. <br />  
  35. <div class="form-group">  
  36.    <label for="password" class="col-md-3 control-label">Contact</label>  
  37. <div class="col-md-9">  
  38.    @Html.PasswordFor(x => x.Contact, new { @class = "form-control", placeholder = "Password" })  
  39.    @Html.ValidationMessageFor(x => x.Contact, "Please enter Contact"new { @class = "text-   danger", style = "   display:none" })  
  40. </div>  
  41. </div>  
  42. <div class="form-group">  
  43.    <span id="spnMessage" class="text-danger">@TempData["Message"]</span>  
  44.    <br />  
  45. <!-- Button -->  
  46. <div class="col-md-offset-3 col-md-9">  
  47.    <button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i> Sign Up</button>  
  48.    <span style="margin-left:8px;"></span>  
  49. </div>  
  50. </div>  
  51. }  
Step 3 - jQuery code
  1. <script>  
  2.     $(document).ready(function() {  
  3.         //to allow only numberic  
  4.         $('#Contact').keypress(function(e) {  
  5.             NumericOnly(e);  
  6.         });  
  7.     });  
  8.     //to check all fields where user enter correct or not   
  9.     // if not entered correct ,it will prevent to sumbit form  
  10.     function ValidateUser() {  
  11.         event = event || window.event || event.srcElement;  
  12.         var return_val = true;  
  13.         if ($('#FirstName').val().trim() == '') {  
  14.             $('#FirstName').next('span').show();  
  15.             return_val = false;  
  16.         } else {  
  17.             $('#FirstName').next('span').hide();  
  18.         }  
  19.         if ($('#LastName').val().trim() == '') {  
  20.             $('#LastName').next('span').show();  
  21.             return_val = false;  
  22.         } else {  
  23.             $('#LastName').next('span').hide();  
  24.         }  
  25.         if ($('#Email').val().trim() == '') {  
  26.             $('#Email').next('span').text('Please enter Email').show();  
  27.             return_val = false;  
  28.         } else {  
  29.             $('#Email').next('span').hide();  
  30.             if (fnValidateEmail($('#Email').val().trim()) == false) {  
  31.                 $('#Email').next('span').text('Please enter valid Email').show();  
  32.                 return_val = false;  
  33.             } else {  
  34.                 $('#Email').next('span').text('Please enter Email').hide();  
  35.             }  
  36.         }  
  37.         if ($('#Password').val().trim() == '') {  
  38.             $('#Password').next('span').show();  
  39.             return_val = false;  
  40.         } else {  
  41.             $('#Password').next('span').hide();  
  42.             if (PasswordStrengthCheck($('#Password').val().trim()) == false) {  
  43.                 return_val = false;  
  44.             }  
  45.         }  
  46.         if ($('#Contact').val().trim() == '') {  
  47.             $('#Contact').next('span').show();  
  48.             return_val = false;  
  49.         } else {  
  50.             $('#Contact').next('span').hide();  
  51.         }  
  52.         if (!return_val) {  
  53.             event.preventDefault();  
  54.         }  
  55.     }  
  56.     // to check password strength   
  57.     function PasswordStrengthCheck(password) {  
  58.         var return_val = true;  
  59.         if (password != '') {  
  60.             if (password.length < 8) {  
  61.                 $('#Password').next('span').text('Be at least 8 characters').show();  
  62.                 $('#Password').focus();  
  63.                 return_val = false;  
  64.             } else if (!password.match(/[A-z]/)) {  
  65.                 $('#Password').next('span').text('At least one letter').show();  
  66.                 $('#Password').focus();  
  67.                 return_val = false;  
  68.             } else if (!password.match(/[A-Z]/)) {  
  69.                 $('#Password').next('span').text('At least one uppercase alphabet').show();  
  70.                 $('#Password').focus();  
  71.                 return_val = false;  
  72.             } else if (!password.match(/[a-z]/)) {  
  73.                 $('#Password').next('span').text('At least one lowercase alphabet').show();  
  74.                 $('#Password').focus();  
  75.                 return_val = false;  
  76.             } else if (!password.match(/\d/)) {  
  77.                 $('#Password').next('span').text('At least one number').show();  
  78.                 $('#Password').focus();  
  79.                 return_val = false;  
  80.             } else if (!password.match(/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/)) {  
  81.                 $('#Password').next('span').text('At least one special character').show();  
  82.                 $('#Password').focus();  
  83.                 return_val = false;  
  84.             } else {  
  85.                 $('#Password').next('span').text('').hide();  
  86.             }  
  87.         } else {  
  88.             $('#Password').next('span').text('Please enter Password').show();  
  89.             return_val = false;  
  90.         }  
  91.         return return_val;  
  92.     };  
  93.     // to check email formate   
  94.     function fnValidateEmail(email) {  
  95.         var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;  
  96.         return expr.test(email);  
  97.     };  
  98.   
  99.     function NumericOnly(e) {  
  100.         var regex = new RegExp("^[0-9]+$");  
  101.         var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);  
  102.         if (regex.test(str)) {  
  103.             return true;  
  104.         }  
  105.         e.preventDefault();  
  106.         return false;  
  107.     };  
  108. </script>  
Using this jQuery code, we can validate before submitting the form to the server.