Donate

ASP.NET MVC 5 Client-Side Form Validation Using jQuery And Bootstrap With Model Class

Here's a simple client side validation in ASP.NET MVC 5. By default, the application's unobtrusive validation has been set to true in web.config file. For this demo, I did not include a saving process to database. I just added a simple view to indicate a success if the model passed to the controller is valid. See files and screenshots below:

Registration.cs (This should be created inside the Model folder)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Registration
    {
        [Required(ErrorMessage = "You must provide your first name")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
 
        [Required(ErrorMessage = "You must provide your last name")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
 
        [Required(ErrorMessage = "You must provide your middle name")]
        [Display(Name = "Middle Name")]
        public string MiddleName { get; set; }
 
        [Required(ErrorMessage = "You must provide your email address")]
        [Display(Name = "E-Mail address")]
        [DataType(DataType.EmailAddress)]
        [EmailAddress]
        public string EmailAddress { get; set; }
 
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
 
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [System.ComponentModel.DataAnnotations.CompareAttribute("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPasword { get; set; }
    }

HomeController.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Index(Registration registration)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("RegistrationSuccess");
            }
 
            return View();           
        }
 
        public ActionResult RegistrationSuccess()
        {
            return View();
        }
    }

Index.cshtml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
@model MVCFormValidation.Models.Registration
 
<div class="row">       
 
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "frmInput", @class = "form-horizontal" }))
    {           @Html.AntiForgeryToken()
                @Html.ValidationSummary(false)
                <div class="form-group">
                    @Html.LabelFor(m => m.FirstName, new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", @id = "fname", @name = "fname" })
                        @Html.ValidationMessageFor(m => m.FirstName, null)
                    </div>                   
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.MiddleName, new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.MiddleName, new { @class = "form-control", @id = "mname", @name = "mname" })       
                        @Html.ValidationMessageFor(m => m.MiddleName)                 
                    </div>
                </div>
                <div class="form-group">
                    <label for="lname" class="control-label col-md-2">Last Name:</label>
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control", @id = "lname", @name = "lname" }) 
                        @Html.ValidationMessageFor(m => m.LastName)   
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-md-2" for="email">Email:</label>
                    <div class="col-md-10" >
                        @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control", @id = "email", @name = "email" })
                        @Html.ValidationMessageFor(m => m.EmailAddress) 
                    </div>
                </div>
                <div class="form-group">
                    <label for="Password" class="control-label col-md-2">Password</label>
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @id = "password", @name = "password" })
                        @Html.ValidationMessageFor(m => m.Password)   
                    </div>
                </div>
                <div class="form-group">
                    <label for="ConfirmPassword" class="control-label col-md-2">Confirm Password</label>
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.ConfirmPasword, new { @class = "form-control", @id = "confirmpassword", @name = "confirmpassword" })
                        @Html.ValidationMessageFor(m => m.ConfirmPasword)    
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-md-10">
                        <button type="submit" class="btn btn-primary">Register</button>
                        <button type="button" class="btn">Cancel</button>
                    </div>
                </div>
    }
</div>

CustomBootstrapValidation.js (This should be created inside the Scripts folder
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//bootstrap styling 3.x 
$(function () {
    // set formatting for validation summary
    $('.validation-summary-errors').each(function () {
        $(this).addClass('alert');
        $(this).addClass('alert-danger');
    });
 
    $("#frmInput").submit(function () {
        if ($(this).valid()) {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length == 0) {
                    $(this).removeClass('has-error');
                    $(this).addClass('has-success');
                }
            });
        }
        else {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).removeClass('has-success');
                    $(this).addClass('has-error');
                }
            });
            $('.validation-summary-errors').each(function () {
                if ($(this).hasClass('alert-danger') == false) {
                    $(this).addClass('alert');
                    $(this).addClass('alert-danger');
                }
            });
        }
    });
});
 
/* set defaults */
var page = function () {
    //Update the validator
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest(".form-group").addClass("has-error");
            $(element).closest(".form-group").removeClass("has-success");
        },
        unhighlight: function (element) {
            $(element).closest(".form-group").removeClass("has-error");
            $(element).closest(".form-group").addClass("has-success");
        }
    });
}();

Screenshots:
ASP.NET MVC 5 Client-Side Form Validation Using jQuery And Bootstrap With Model Class
ASP.NET MVC 5 Client-Side Form Validation Using jQuery And Bootstrap With Model Class
ASP.NET MVC 5 Client-Side Form Validation Using jQuery And Bootstrap With Model Class
Note: Make sure to bundle the external javascript file in BundleConfig.cs and Render it in Layout.cshtml.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.