Friday, 15 April 2016

Create Custom Data Annotation Validators in MVC



To create a custom data annotation validator follow these gudelines:
1)    Your class has to inherit from System.ComponentModel.DataAnnotations.ValidationAttribute class.
2)    Override bool IsValid(object value) method and implement validation logic inside 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).


5 comments:

  1. the blog is very interesting and will be much useful for us. thank you for sharing the blog with us. please keep on updating.
    Informatica Training in Chennai Adyar

    ReplyDelete
  2. I have read your blog..Its really an awesome article with useful content..keep sharing.
    Best VLSI Project Center in Chennai | VLSI Project Center in Velachery

    ReplyDelete
  3. Wow! It was the best article , actually you have posted something new compared to others, because I read many articles related to this topic but I only get impressed with your post only, keep posting.
    Blue Prism Training Institute in Chennai | RPA Training Institute in Chennai | UiPath Training in Chennai

    ReplyDelete