Enable client-side validation in your ASP.NET Core MVC app
✅ 1. Add Required Scripts in Your
Layout (_Layout.cshtml)
Make sure these scripts are included before the closing </body>
tag:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation-unobtrusive@4.0.0/dist/jquery.validate.unobtrusive.min.js"></script>
These scripts are necessary for enabling jQuery
Unobtrusive Validation.
✅ 2. Enable Unobtrusive
Validation in _ViewImports.cshtml
If it’s not already added, ensure the following line is in
your _ViewImports.cshtml:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
✅ 3. Use asp-validation-for in
Your Razor View
Update your Create.cshtml form fields like this:
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name"
class="form-control" />
<span asp-validation-for="Name"
class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email"
class="form-control" />
<span asp-validation-for="Email"
class="text-danger"></span>
</div>
<!-- Repeat for
other fields similarly -->
<button type="submit"
class="btn btn-primary">Submit</button>
</form>
✅ 4. Enable Client Validation in Startup.cs
(if ASP.NET Core)
In ConfigureServices method:
services.AddControllersWithViews()
.AddViewOptions(options =>
{
options.HtmlHelperOptions.ClientValidationEnabled = true;
});
For legacy ASP.NET MVC (non-Core), make sure the following
is in your web.config:
xml
<appSettings>
<add key="ClientValidationEnabled"
value="true" />
<add key="UnobtrusiveJavaScriptEnabled"
value="true" />
</appSettings>
✅ 5. Style the Error Messages
(Optional)
You can add this in your styles block or CSS:
.text-danger {
font-size: 14px;
color: red;
}
✅ Result:
Now, validations like [Required], [EmailAddress], [Phone], [Range],
etc. will work instantly on the client-side, preventing form submission
until errors are fixed.
No comments: