Validate fields not in model class or entity using MVC5 MVC has great inbuilt feature for validate fields. You need to apply validation attribute to each field in model or entity and entity Framework will automatically consider that validation on view. To enable client side validation you must include three js file 1-jquery core, 2-jquery validate, 3-unobtrusive (responsible for call unobtrustive validation).
Note : This is client side validation only, you have to validate field manually on server side.
In this article we share important trick for validate not model fields. When we apply validation in model it will render like this. All rendered validation are starts with data-val prefix.
<input type="text" data-val="true" data-val-required="this field is required" id="firstName">
You can implement custom validation as as IDictionary<string,object> htmlAttributes
new Dictionary<string, object> { { "data-val", "true" }, { "data-val-required", "The Product Sub Category is required" } }
as object htmlAttributes
new { data_val = "true", data_val_required = "Route is required" }
Apply it on Controls
@Html.DropDownList("productSubCategories", (ViewBag.ProductCategories as IEnumerable), "--Select--", new Dictionary { { "data-val", "true" }, { "data-val-required", "The Product Sub Category is required" } })
@Html.DropDownList("productSubCategories", (ViewBag.ProductCategories as IEnumerable), "--Select--", new { data_val = "true", data_val_required = "The Product Sub Category is required" })
@Html.TextBox("Name","", new { data_val = "true", data_val_required = "Name is required" })
 Note: @Html.ValidationMessage("Name") is required to write for generate validation error message

I am not creating any entity because we are validating non model fields
 @Html.TextBox("Name", "", new { data_val = "true", data_val_required = "Name is required" })
 <input type="submit" value="Create" class="btn btn-default" />


Popular posts from this blog

12 opensource and free MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in