Client-side validation
Client-side validation shows form errors instantly in the browser, before anything is sent. This lesson shows how ASP.NET Core turns your data annotations into browser checks, how to switch it on, and why the server must always validate again.
- StartUser typesBrowser checks rules from data-val attributes
- Step 2Errors shown at onceNo request sent until the form is valid
- Step 3Form postedModel binding fills the model
- Step 4Server checks againModelState.IsValid and business rules
- EndSaved or re-shownInvalid input returns the view with errors
How it works
The same attributes that drive server validation, such as [Required], [StringLength], [Range], [EmailAddress] and [Compare], are written into the form as data-val-* attributes by the input tag helper. A small script reads them and checks fields as the user types and before submit.
The default MVC template ships the scripts: jQuery, jQuery Validation and jQuery Validation Unobtrusive, loaded by the _ValidationScriptsPartial view.
The model and the form
public class SignUpModel
{
[Required, EmailAddress]
public string Email { get; set; } = "";
[Required, StringLength(100, MinimumLength = 8)]
[DataType(DataType.Password)]
public string Password { get; set; } = "";
[Compare(nameof(Password), ErrorMessage = "The passwords do not match.")]
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; } = "";
}The view
@model SignUpModel
<form asp-action="SignUp" method="post">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Email"></label>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
<label asp-for="Password"></label>
<input asp-for="Password" />
<span asp-validation-for="Password"></span>
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" />
<span asp-validation-for="ConfirmPassword"></span>
<button type="submit">Create account</button>
</form>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}Always validate on the server too
- Anyone can turn off JavaScript or send a request with curl, so client checks are only for convenience.
- Keep if (!ModelState.IsValid) return View(model); in every POST action.
- Checks that need data, such as "email already registered", run on the server; [Remote] can call an action to check while typing.
- Custom attributes validate on the server automatically; for browser checks they also need a small client adapter.
Interview question
If you have client-side validation, do you still need server-side validation?
Yes, always. Client-side validation only improves the user experience; it can be bypassed by disabling JavaScript or posting directly to the endpoint. The server must check ModelState.IsValid and any business rules before saving. ASP.NET Core makes this easy because the same data annotation attributes drive both.
Want the full details? Read the official Microsoft documentation for this topic.