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

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))




Join the conversation! Your thoughts help the community grow.