ASP.NET MVC Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

ASP.NET MVC Input Validation

Back to: ASP.NET MVC Tutorial

ASP.NET MVC offers several ways to validate user input in a web application, ensuring that only valid data is processed and stored. Here’s an overview of key methods to implement input validation:

1. Data Annotations (Server-Side Validation)

Data annotations are attributes applied directly to model properties. ASP.NET MVC uses these to perform validation both on the client and server. Common data annotations include:

  • [Required]: Ensures the field is not empty.
  • [StringLength]: Sets the maximum length of a string.
  • [Range]: Validates that a numeric field falls within a specified range.
  • [EmailAddress]: Ensures the input is a valid email format.
  • [RegularExpression]: Validates the field with a specific regex pattern.
  • [Compare]: Compares two fields (useful for password confirmation).

Example:

public class UserModel
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[StringLength(100, ErrorMessage = "Email length can't be more than 100.")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Range(18, 100, ErrorMessage = "Age must be between 18 and 100")]
public int Age { get; set; }
}

2. Custom Validation Attributes

For custom rules, you can create custom validation attributes by inheriting from ValidationAttribute. This is useful for unique rules specific to your application's needs.

Example:

public class CustomAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int age = (int)value; if (age < 18 || age > 100)
{
return new ValidationResult("Age must be between 18 and 100.");
}
return ValidationResult.Success;
}
}
 public class UserModel
{
 [CustomAge]
 public int Age { get; set; }
}

3. Model State Validation in Controllers

In your controller action, check ModelState.IsValid to verify if all model validations have passed. If validation fails, return the view with validation errors; otherwise, proceed with the logic.

Example:

[HttpPost]
public IActionResult Register(UserModel model)
{
if (ModelState.IsValid)
{
// Proceed with registration
}
else
{
 // Return view with errors return View(model);
}
}

4. Client-Side Validation (Unobtrusive Validation)

ASP.NET MVC’s unobtrusive JavaScript works alongside data annotations for client-side validation, reducing round trips to the server. This relies on jQuery Validation and is automatically enabled if scripts and libraries are included.

Ensure that these are in your layout or view:

html
//~/Scripts/jquery.validate.min.js //~/Scripts/jquery.validate.unobtrusive.min.js

5. Remote Validation

Remote validation makes AJAX calls to check if a value is unique or meets certain criteria without submitting the form. Use [Remote] attribute in the model and define the validation method in the controller.

Example:

public class UserModel
{
[Remote("IsEmailAvailable", "Account", ErrorMessage = "Email already taken")]
public string Email { get; set; }
}
public class AccountController : Controller {
public JsonResult IsEmailAvailable(string email)
{
bool isAvailable = !db.Users.Any(u => u.Email == email); return Json(isAvailable);
}
}

 

Summary

ASP.NET MVC provides a comprehensive framework for input validation using data annotations, custom validation attributes, client-side validation, remote validation, and external libraries like FluentValidation. Combined, these tools help ensure data integrity and a better user experience.

Scroll to Top