Press "Enter" to skip to content

Validation In ASP.NET MVC Model Binding Using jQuery

Md Saud 2

Sharing is caring !!

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.

public class Registration {
public string FirstName {
get;
set;
}
public string LastName {
get;
set;
}
public int UserId {
get;
set;
}
public string Password {
get;
set;
}
public string Email {
get;
set;
}
public string Contact {
get;
set;
}
}

Step 2

In View model Registration.cshtml,

@using (Html.BeginForm("Registration", "Login", FormMethod.Post, new {onsubmit="ValidateUser();"}))
{
@Html.TextBoxFor(x => x.FirstName, "", new { @class = "form- control", placeholder = "First Name" }) @Html.ValidationMessageFor(x => x.FirstName, "Please enter First Name", new { @class = "text- danger", style = "display:none" })
 
@Html.TextBoxFor(x => x.LastName, "", new { @class = "form-control", placeholder = "Last Name" }) @Html.ValidationMessageFor(x => x.LastName, "Please enter Last Name", new { @class = "text- danger", style = "display:none" })
 
@Html.TextBoxFor(x => x.Email, "", new { @class = "form-control", placeholder = "Email" }) @Html.ValidationMessageFor(x => x.Email, "Please enter Email", new { @class = "text- danger", style = "disp lay:none" })
 
@Html.PasswordFor(x => x.Password, new { @class = "form- control", placeholder = "Password", onblur = "Pass wordStrength();" }) @Html.ValidationMessageFor(x => x.Password, "Please enter Password", new { @class = "text- danger", style = "display:none" })
 
@Html.PasswordFor(x => x.Contact, new { @class = "form-control", placeholder = "Password" }) @Html.ValidationMessageFor(x => x.Contact, "Please enter Contact", new { @class = "text- danger", style = " display:none" })
@TempData["Message"]
}

Step 3 – jQuery code

 
    $(document).ready(function() {  
        //to allow only numberic  
        $('#Contact').keypress(function(e) {  
            NumericOnly(e);  
        });  
    });  
    //to check all fields where user enter correct or not   
    // if not entered correct ,it will prevent to sumbit form  
    function ValidateUser() {  
        event = event || window.event || event.srcElement;  
        var return_val = true;  
        if ($('#FirstName').val().trim() == '') {  
            $('#FirstName').next('span').show();  
            return_val = false;  
        } else {  
            $('#FirstName').next('span').hide();  
        }  
        if ($('#LastName').val().trim() == '') {  
            $('#LastName').next('span').show();  
            return_val = false;  
        } else {  
            $('#LastName').next('span').hide();  
        }  
        if ($('#Email').val().trim() == '') {  
            $('#Email').next('span').text('Please enter Email').show();  
            return_val = false;  
        } else {  
            $('#Email').next('span').hide();  
            if (fnValidateEmail($('#Email').val().trim()) == false) {  
                $('#Email').next('span').text('Please enter valid Email').show();  
                return_val = false;  
            } else {  
                $('#Email').next('span').text('Please enter Email').hide();  
            }  
        }  
        if ($('#Password').val().trim() == '') {  
            $('#Password').next('span').show();  
            return_val = false;  
        } else {  
            $('#Password').next('span').hide();  
            if (PasswordStrengthCheck($('#Password').val().trim()) == false) {  
                return_val = false;  
            }  
        }  
        if ($('#Contact').val().trim() == '') {  
            $('#Contact').next('span').show();  
            return_val = false;  
        } else {  
            $('#Contact').next('span').hide();  
        }  
        if (!return_val) {  
            event.preventDefault();  
        }  
    }  
    // to check password strength   
    function PasswordStrengthCheck(password) {  
        var return_val = true;  
        if (password != '') {  
            if (password.length < 8) {  
                $('#Password').next('span').text('Be at least 8 characters').show();  
                $('#Password').focus();  
                return_val = false;  
            } else if (!password.match(/[A-z]/)) {  
                $('#Password').next('span').text('At least one letter').show();  
                $('#Password').focus();  
                return_val = false;  
            } else if (!password.match(/[A-Z]/)) {  
                $('#Password').next('span').text('At least one uppercase alphabet').show();  
                $('#Password').focus();  
                return_val = false;  
            } else if (!password.match(/[a-z]/)) {  
                $('#Password').next('span').text('At least one lowercase alphabet').show();  
                $('#Password').focus();  
                return_val = false;  
            } else if (!password.match(/\d/)) {  
                $('#Password').next('span').text('At least one number').show();  
                $('#Password').focus();  
                return_val = false;  
            } else if (!password.match(/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/)) {  
                $('#Password').next('span').text('At least one special character').show();  
                $('#Password').focus();  
                return_val = false;  
            } else {  
                $('#Password').next('span').text('').hide();  
            }  
        } else {  
            $('#Password').next('span').text('Please enter Password').show();  
            return_val = false;  
        }  
        return return_val;  
    };  
    // to check email formate   
    function fnValidateEmail(email) {  
        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})(\]?)$/;  
        return expr.test(email);  
    };  
  
    function NumericOnly(e) {  
        var regex = new RegExp("^[0-9]+$");  
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);  
        if (regex.test(str)) {  
            return true;  
        }  
        e.preventDefault();  
        return false;  
    };  

Using this jQuery code, we can validate before submitting the form to the server.

Sharing is caring !!

  1. Tauheed Alam Tauheed Alam

    Very UseFul

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

shares