Thursday, June 13, 2013

How to write a Regular expression for case insensitive search for email with fixed domain in MVC4

I was trying to search for a way to write a regular expression which can validate my email string. My email string is something of the kind xxx@gmail.com which means while the first part of the string may change the later part is a fixed domain. I wanted this to be case insensitive validation so that an email XxXx@GmaIL.com is also validated properly.

To achieve the same we need to do it in three steps

First we need to define a custom attribute which will be used to validate the expression

Step 1 :

public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable

 
 
{
 
public IgnoreCaseRegularExpressionAttribute(string pattern)

: base("(?i)" + pattern)
 
 

{ }
 
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 
 

{
 
var rule = new ModelClientValidationRule

 
 
{
 
ValidationType = "ignorecaseregex",
 
 

ErrorMessage = ErrorMessage

};
 
 
rule.ValidationParameters.Add("pattern", Pattern.Substring(4));

yield return rule;
 
 

}

}

Step 2:
The validation mentioned in the step 1 need to be registered in a script file


jQuery.validator.unobtrusive.adapters.add('ignorecaseregex', ['pattern'], function (options) {

options.rules['icregex'] = options.params;

options.messages['icregex'] = options.message;



});
jQuery.validator.addMethod('ignorecaseregex', function (value, element, params) {

var match;

if (this.optional(element)) {

return true;



}
match = new RegExp(params.pattern, 'i').exec(value);

return (match && (match.index === 0) && (match[0].length === value.length));

}, '');

this script file needs to be loaded on the form where your property is used.

Step 3 :This is the final step where you are now ready to use the  IgnorecaseRegularExpressionAttribute attribute.This can be used on the property where we want to do a case insensitive validation for e.g.

[IgnorecaseRegularExpression("^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-0_]+)*@gmail+(\\.com)", ErrorMessage = "Not a valid email.")]

public string DemoPropertyName { get; set; }


 



No comments: