public class HomeController : Controller { public ActionResult Index() { ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider()); return View(); } [HttpPost] public ActionResult Index(Person objPerson) { if (ModelState.IsValid) { } return View(objPerson); } } public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider { protected override IEnumerable<modelvalidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<attribute> attributes) { if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "FirstName") { attributes = new List<attribute>() { new RequiredAttribute() }; } return base.GetValidators(metadata, context, attributes); } } public class Person { [RegularExpression(@"^[a-zA-Z0-9\-\s]*$")] public string FirstName { get; set; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)