Hi
Below i have 2 Data Annotations for 2 separate fields Id & Description. I want only 1 class for both, Methods should be different.
Is it possible?
[Key]
[Required(ErrorMessage = "Id can not be blank.")]
[StringLength(4, ErrorMessage = "Max length should be less than or equal to 4.")]
[RegularExpression(@"^[a-zA-Z][a-zA-Z ]+$", ErrorMessage = "Special Characters not allowed")]
[Remote("IsExist", "Location", ErrorMessage = "Id already exists")]
[Display(Name = "Id")]
public string Id { get; set; }
[DataType(DataType.Text)]
[Required(ErrorMessage = "Description can not be blank.")]
[StringLength(25, ErrorMessage = "Max length should be less than or equal to 25.")]
[RegularExpression(@"^[a-zA-Z][a-zA-Z ]+$", ErrorMessage = "Special Characters not allowed")]
[Display(Name = "Description")]
public string Description { get; set; }
Below is for 1 Data Annotation. Can the Annotation for ID can be done in this same class.
So that these can be used separately where required.
public class DescriptionAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (
new RegularExpressionAttribute(@"^[a-zA-Z][a-zA-Z ]+$") { ErrorMessage = "Special Characters not allowed" }.IsValid(value)
&& new RequiredAttribute { ErrorMessage = "Description can not be blank." }.IsValid(value)
&& new StringLengthAttribute(25) { ErrorMessage = "Max length should be less than or equal to 25." }.IsValid(value)
&& new DataTypeAttribute(DataType.Text).IsValid(value)
)
{
return true;
}
else
{
return false;
}
}
}