Custom Name attribute class :
We have created a separate folder to include class files. The class file for Custom Annotation Attribute looks like below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//We have include the below namespace to use DataAnnotations
using System.ComponentModel.DataAnnotations;
namespace CustomValidation.CustomNameValidator
{
//Inherited the base class ValidationAttribute to create our own Custom Attribute.
public class CustomNameValidator : ValidationAttribute
{
private readonly int maxWords;
//The constructor accepts single parameter i.e. maximum limit to check the count of words.
//This can be used to validate FirstName to have specified number of words.
//We are also passing a default message to base class. This is default message.
public CustomNameValidator(int maximumLimit)
: base("{0} should be less than " + maximumLimit + " letters.")
{
//We are setting a private variable MaxWords with maximum limit which is specified while defining attribute.
maxWords = maximumLimit;
}
//We have override the IsValid method which accepts value and ValidationContext object.
//value is the input provided by user from Form. The value which is posted from form.
//Validation context object has details about the property on which this attribute is used.
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//Checking if the value is null.
if (value != null)
{
//casting the object value to string.
var valueAsString = value.ToString();
//comparing the input value length and the length specified while defining attributes.
if (valueAsString.Length < maxWords)
{
//If the input length is within the maximum length allowed then attribute will return Success.
return ValidationResult.Success;
}
else
{
//If the input length is not withing the maximum length, then error message is returned.
//As we have passed the default message above. We have passed a placeholder with it.
//The display name is passed as parameter. And error message is displayed.
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
else
{
//If value is null, we are returning error message. This validation works like Required attribute.
//In below line we are passing display name and message as well.
return new ValidationResult("" + validationContext.DisplayName + " is manadatory field");
}
}
}
}

The above code validates the string input. It validates the input for its count. It also checks if value is null or not. The code returns the error message if validation fails.