Never trust user input. Professional validation includes both Client-Side and Server-Side checks. We prevent "Garbage Data" from ever hitting our SQL Server.
public class RegisterViewModel {
[Required(ErrorMessage = "Full Name is mandatory.")]
[StringLength(100, MinimumLength = 3)]
public string FullName { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
[Range(18, 99)]
public int Age { get; set; }
}
What if you need to validate that a Date is in the past? Or that a username is unique? This requires a custom attribute.
public class PastDateAttribute : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext context) {
if (value is DateTime dt && dt >= DateTime.Now) {
return new ValidationResult("Date must be in the past!");
}
return ValidationResult.Success;
}
}
Use the [Remote] attribute to call a server-side action via AJAX while the user is still typing. This is perfect for "Check Username Availability" without refreshing the entire registration form. It provides the best UX while ensuring data integrity.