How can make custome validation in MVC?

As you know there are lots of default validators in MVC same as Range, Requires and etc… But you may need to create your own validators for special purpose. Today I will show you how to create your own validator.

Let start, I want to make a validator that checks the string input and if the string contains these two characters “(“, “)”, shows an appropriate message to the user.

First you need to make a class that inherits from the ValidationAttribute and then overwrite the functions :

namespace System.ComponentModel.DataAnnotations
{

   public class CheckContentAttribute : ValidationAttribute
{
public CheckContentAttribute()
:base("{0} Check you input sting , it should not contain these
 two charachters : '(' and ')'")
{

}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
    if (value != null)
    {
        var valueAsString = value.ToString();
       if (valueAsString.Contains("(")  ||valueAsString.Contains(")"))
        {
            var errorMessage = FormatErrorMessage(
            validationContext.DisplayName);
            return new ValidationResult(errorMessage);
        }
    }
    return ValidationResult.Success;
}
}
}

And now you can use this validator :

 public class Info_AdminUsers
    {
        public int Id { get; set; }

        [Required]
        [CheckContent()]
        public string UserName { get; set; }

        [Required]
        [StringLength(160,MinimumLength=3)]
        public string Password { get; set; }

    }

See it is much more easier than you thought , Am I right?

Advertisement