Wanting to create custom data annotation validation. Are there any useful guides / samples on how to create them?
Firstly:
StringLength with minimum and maximum length. I'm aware .NET 4 can do this, but want to do the same in .NET 3.5, if possible being able to define minimum length only (at least x chars), maximum length only (up to x chars), or both (between x and y chars).
Secondly:
Validation using modulus arithmetic - if the number is a valid length, I wish to validate using the Modulus 11 algorithm (I have already implemented it in JavaScript, so I guess it would just be a simple porting?)
Update:
Solved second problem, was just a case of copying over the JavaScript implementation and making a few tweaks, so don't need a solution for that.
The MVC framework has great extensibility features and because of this we can create our own customized data annotation attributes.
To create a custom validation attributeIn Solution Explorer, right-click the App_Code folder, and then click Add New Item. Under Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used.
DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
So making the attributes reusable we are going to place all the custom annotation logic in one common place/folder, say Attributes, as we know all the validation annotations (such as Range, StringFormat ) ultimately derive from the ValidationAttribute base class. This base class is abstract and resides under System.
To create a custom data annotation validator follow these gudelines:
System.ComponentModel.DataAnnotations.ValidationAttribute
class.bool IsValid(object value)
method and implement validation logic inside it.That's it.
Sometimes developers check that value is not null/empty and return false. This is usually incorrect behaviour, because that's on Required
validator to check which means that your custom validators should only validate non-null data but return true
otherwise (see example). This will make them usable on mandatory (required) and non-mandatory fields.
public class StringLengthRangeAttribute : ValidationAttribute { public int Minimum { get; set; } public int Maximum { get; set; } public StringLengthRangeAttribute() { this.Minimum = 0; this.Maximum = int.MaxValue; } public override bool IsValid(object value) { string strValue = value as string; if (!string.IsNullOrEmpty(strValue)) { int len = strValue.Length; return len >= this.Minimum && len <= this.Maximum; } return true; } }
All properties can be set in attribute as you wish to set them.
Some examples:
[Required] [StringLengthRange(Minimum = 10, ErrorMessage = "Must be >10 characters.")] [StringLengthRange(Maximum = 20)] [Required] [StringLengthRange(Minimum = 10, Maximum = 20)]
When a particular property isn't set, its value is set in the constructor, so it always has a value. In above usage examples I deliberately added the Required
validator as well, so it's in sync with the above caution I've written.
So this validator will still work on your model value that's not required, but when it's present it validates (think of a text field in a web form, that's not required, but if a user enters a value in, it has to be valid).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With