using System;
using System.ComponentModel.DataAnnotations;
public class User
{
[Required]
public string Username { get; set; }
[EmailAddress]
public string Email { get; set; }
}
var user = new User { Username = "JohnDoe", Email = "invalid-email" };
var context = new ValidationContext(user, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(user, context, results, true);
<form asp-action="Submit" method="post">
<input asp-for="Username" />
<span asp-validation-for="Username"></span>
<button type="submit">Submit</button>
</form>
public class Product
{
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
}
var product = new Product { Name = "A" };
var context = new ValidationContext(product, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(product, context, results, true);