Emailexcludehashattribute: Emailexcludehashattribute Validationattribute Validationresult Validationcontext
Emailexcludehashattribute: Emailexcludehashattribute Validationattribute Validationresult Validationcontext
Steps:
1. Create a class for the custom validator followed by Attribute. Here, for example:
EmailExcludeHashAttribute
using System;
using System.ComponentModel.DataAnnotations;
namespace SampleMVCApp.Custom.DataAnnotations
{
public class EmailExcludeHashAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if(value != null)
{
if(value is string)
{
if(value.ToString().Contains("#"))
{
return new ValidationResult("Hash is not recommended for email id. Please remove hash(\"#\") and try
again");
}
else
{
return ValidationResult.Success;
}
}
}
return ValidationResult.Success;
}
}
}
namespace SampleMVCApp.Custom.Helpers
4. Build the solution and use the newly created html helper in cshtml file as below:
5. Before using the newly created html helper, we need to import the namespace used for the
creation of this cutom html helper.
@using SampleMVCApp.Custom.Helpers;
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
@Html.Image("https://titasiregar.files.wordpress.com/2009/04/firefox_logo_small.png", "Firefox logo")
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
Screen-shot below: