How to add Custom validators in asp.net MVC4

How to add custom validators in mvc4?

Create MVC project



Select basic project
 


Add Sample controller
 


Add “Customer.cs” file to use as model while creating View.
 


Add View in Sample Controller
 
 
Select strongly type view and select customer.cs
 


Now Add Required Attribute on property of customer - above Name

Required inbuilt property for validation after adding using System.ComponentModel.DataAnnotations;

This required attribute make that textbox mandatory.

public class Customer
{
        [
Required]
       
public string Name { get; set; }
}

We have to add custom validator like need some special word in textbox value.

Then just write [RequiredSpecialWord] and press ctrl + . and create class

Now check “RequiredSpecialWord.cs” in model folder. It inherited from ValidationAttribute class

Now override method isValid in RequiredSpecialWord.cs

Check below code

public class RequiredSpecialWord:ValidationAttribute

{

        private string _word;

        public RequiredSpecialWord(string word)

        {

            _word = word;

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)

        {

            if (Convert.ToString(value).Contains(_word))

            {

                return ValidationResult.Success;

            }

            else

            {

                return new ValidationResult(_word +" not included");

            }

      }

}

Check ModelState.IsValid property in controller.

public ActionResult contact(Customer cust)

{

     if (!ModelState.IsValid)

    {

         return View("index");

    }

   return View();

}

ModelState.IsValid checks that your validation are valid or not.

Now just run your project and add sample/Index in your browser url after localhost.

And see output

 

After clicking submit button. You will get below result. Because we added Required validator and we have not put anything in textbox.
 


Now I entered text as aaaa and pressed submit, then I got below result
 


That is Ram not included. Ram is normal word it can be Rob, Dan anything.

To change Ram word use below code in customer.cs
 

[RequiredSpecialWord("Ram")]

public string Name { get; set; }

Find attached source code, if you get any issue feel free to contact me.