Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,820 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am using model validation in a class and I have used attributes in few properties. I have already get the attributes name by property name but it gives me all attributes from a property but I need only that attribute name which got error like ex- if Required attribute fires then it should give only me Required attribute name not all attributes.I am sharing my code and thanks in advance.
public class ProductModel
{
[PrimaryKey, AutoIncrement]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please Enter Product Name")]
public string ProductName { get; set; }
[Required(ErrorMessage = "Please Enter Quantity")]
[RegularExpression("^[0-9]*$", ErrorMessage = "Please Enter Numeric Values in Quantity")]
[Range(1, int.MaxValue, ErrorMessage = "Please enter a value greater than 0")]
public string Quantity { get; set; }
}
public static bool IsFormValid()
{
var model="ProductModel";
var errors = new List<ValidationResult>();
var context = new ValidationContext(model);
bool isValid = Validator.TryValidateObject(model, context, errors, true);
if (isValid == false)
{
ShowValidationFields(errors, model);
}
return errors.Count() == 0;
}
private static void ShowValidationFields(List<ValidationResult> errors, object model)
{
if (model == null) { return; }
foreach (var error in errors)
{
var PropName = error.MemberNames.FirstOrDefault().ToString();
Type type = model.GetType().UnderlyingSystemType;
var Validation = type.GetProperty(PropName).GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
--here i am getting all attributes name assign in a property
}
}
Try identifying the attributes by error messages:
var Validation = type
.GetProperty( PropName )
.GetCustomAttributes( false )
.OfType<ValidationAttribute>( )
.Where( a => a.ErrorMessage == error.ErrorMessage )
.ToDictionary( a => a.GetType( ).Name, a => a );