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

2 thoughts on “How can make custome validation in MVC?”

  1. I don’t know the MVC. Can you indicate me place where IsValid() method is called in example “how it use” ?

  2. Hi paweln66,
    The isvalid () function is called automatically and you do not need to call it. You just need to put [CheckContent ()] above the property that want to be validated by this function. Please take a look at the bottom of the current post you can see my example.
    Do not hesitate to contact me 

Leave a Reply to paweln66 Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s