Based on Parveen's answer, I created a helper static class that can be reused:
public static class ModelState
{
public static List<string> ErrorMessages = new List<string>();
public static bool IsValid<T>(T model) {
var validationContext = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(model, validationContext, results, true))
{
return true;
}
else {
ErrorMessages = results.Select(x => x.ErrorMessage).ToList();
return false;
}
}
}
Form.cs ( "" ) :
private void btnSave_Click(object sender, EventArgs e)
{
var customerResource = GetViewModel();
if (ModelState.IsValid<CustomerResource>(customerResource)) {
}
}
private CustomerResource GetViewModel() {
return new CustomerResource() {
CustomerName = txtName.Text,
Phone = txtPhone.Text
};
}
, asp mvc now