- Client-side form validation
- Server-side form validation
Client-Side Form Validation
Server-Side Form Validation
- Knowledge of ASP.NET MVC5.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of Jquery.
- Knowledge of C# Programming.
- jquery.validate.js
- jquery.validate.unobtrusive.js
static void RegisterRoutes(RouteCollection routes) { routes.MapRoute(...defaults: new { controller = "Home", action = "Register", id = UrlParameter.Optional }); }
public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate.js", "~/Scripts/jquery.validate.unobtrusive.js"));... // JQuery validator. bundles.Add(new ScriptBundle("~/bundles/custom-validator").Include("~/Scripts/script-custom-validator.js")); } }
In the above code, I have added my “jquery.validate.js“, “jquery.validate.unobtrusive.js” & “script-custom-validator.js” scripts as a bundle, which are required for Jquery form validation.
Create a new controller class in “Controllers” folder and name it “HomeController.cs“. Create “Register” method both for HTTP Get and HTTP Post method. Both methods are doing nothing just validating my form inputs basic constraints defined in view model.
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace JqueryFormValidator.Models public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { 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; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
@model JqueryFormValidator.Models.RegisterViewModel @{ViewBag.Title = "Register";} <h2>@ViewBag.Title.</h2> @using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @id = "registerFormId", @class = "form-horizontal", role = "form" \ })) { @Html.AntiForgeryToken() HtmlHelper.UnobtrusiveJavaScriptEnabled = false; <h4>Create a new account.</h4> <hr/> <div class="form-group"> @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger " }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger " }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "text-danger " }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" value="Register" /> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/custom-validator") }
HtmlHelper.UnobtrusiveJavaScriptEnabled = false;
In the above code, I have attach my view model “RegisterViewModel” with my “Register” UI. Notice following line of code i.e.
The above images shows default client side validation response of ASP.NET MVC5 if I set the HtmlHelper.UnobtrusiveJavascriptEnabled property true, which is platform default behavior. To change this default behavior and to activate the Jquery form validation instead, you need to change this property value to false at your form level.
Now first change “HtmlHelper.UnobtrusiveJavaScriptEnabled” property value back to false and create a new file in “Scripts” folder and name it “script-custom-validator.js“. Add the Jquery validator code in it as shown below i.e.
$('#registerFormId').validate({ errorClass: 'help-block animation-slideDown', // You can change the animation class for a different entrance animation - check animations page errorElement: 'div', errorPlacement: function(error, e) { e.parents('.form-group > div').append(error); }, highlight: function(e) { $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error'); $(e).closest('.help-block').remove(); }, success: function(e) { e.closest('.form-group').removeClass('has-success has-error'); e.closest('.help-block').remove(); },
<add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" />
The above properties are set True by default which means MVC 5 platform ensures that client side validation on form validation is on. For jQuery form validation to work, we set “HtmlHelper.UnobtrusiveJavaScriptEnabled = false;” property false in the register form instead of “web.config” file; this means if we set the value false for above property in “web.config” file, then we will disable client side validation across application.Thus, the preferred practice is to disable the property into the form in which you want to use jQuery form validation.
Conclusion
Yury Sobolev is Full Stack Software Developer by passion and profession working on Microsoft ASP.NET Core. Also he has hands-on experience on working with Angular, Backbone, React, ASP.NET Core Web API, Restful Web Services, WCF, SQL Server.