Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

ASP.NET Core Form Validation Example

 Form Validation in ASP.NET Core MVC is handled using Model Validation + Data Annotations + ModelState.

ASP.NET Core provides 3 Levels of Validation:

  1. Model Level Validation (Recommended)
  2. Client-Side Validation
  3. Custom Validation

I'll explain step-by-step professionally 👇


1. Model Validation (Using Data Annotations)

Create Model with Validation Attributes

using System.ComponentModel.DataAnnotations;

public class Employee
{
public int Id { get; set; }

[Required(ErrorMessage ="Name is required")]
public string Name { get; set; }

[Required]
[EmailAddress(ErrorMessage ="Invalid Email")]
public string Email { get; set; }

[Required]
[Range(18,60)]
public int Age { get; set; }

[Required]
[StringLength(10, MinimumLength = 6)]
public string Password { get; set; }
}

Most Important Validation Attributes

AttributePurpose
RequiredMandatory Field
StringLengthMin & Max length
RangeNumeric Range
EmailAddressValidate Email
PhoneValidate Phone
CompareCompare fields
RegularExpressionCustom Pattern
MinLengthMinimum Length
MaxLengthMaximum Length

2. Controller Validation

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Employee emp)
{
if (ModelState.IsValid)
{
// Save Data
return RedirectToAction("Index");
}

return View(emp);
}

What is ModelState.IsValid

ASP.NET automatically checks:

  • Required Fields
  • Format Validation
  • Range Validation

If all correct → ModelState.IsValid = true

Else → false


3. View Validation (Razor Form)

<form asp-action="Create" method="post">

<div>
<label>Name</label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>

<div>
<label>Email</label>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
</div>

<button type="submit">Submit</button>

</form>

Important Tag Helpers

TagPurpose
asp-forBind Model Property
asp-validation-forShow Error
asp-validation-summaryShow All Errors

Show All Errors

<div asp-validation-summary="All"></div>

4. Enable Client Side Validation

Add in _Layout.cshtml

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

This enables:

  • Real-time validation
  • No page reload validation

Required jQuery Files

Already included in ASP.NET Core:

jquery.validate.min.js
jquery.validate.unobtrusive.min.js

Example Full Form

<form asp-action="Create" method="post">

<div asp-validation-summary="All"></div>

<input asp-for="Name" />
<span asp-validation-for="Name"></span>

<input asp-for="Email" />
<span asp-validation-for="Email"></span>

<button type="submit">Submit</button>

</form>

Custom Validation Example

[Required]
[RegularExpression(@"^[a-zA-Z]+$",
ErrorMessage ="Only Characters Allowed")]
public string Name { get; set; }

Compare Validation Example

Password Confirm

[Required]
public string Password { get; set; }

[Compare("Password", ErrorMessage ="Password mismatch")]
public string ConfirmPassword { get; set; }

Server Side vs Client Side

TypeWhere Runs
Client ValidationBrowser
Server ValidationController

Always use Both




Post a Comment

0 Comments