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; }


 



Wednesday, June 12, 2013

Case in-sensitive search in MSCRM 2011

To do a case insensitive search in MSCRM 2011 we need to tweak the query a little bit ,for e.g.

if (!String.IsNullOrEmpty(fieldname)) query.Criteria.AddCondition("fieldname".ToLower(), ConditionOperator.Equal, fieldname.ToLower());
EntityCollection col = service.RetrieveMultiple(query);
Here I am setting the schema name to ToLower() which actually does the trick, hope this help.Leave your comments.

Tuesday, June 4, 2013

Hitting backspace on the jquery datetime control hides it on MSCRM 2011 form/ How to capture the keypress event on a jquery control and overcome the default behavior


I have used jquery hour’s picker/Date picker control on the MSCRM form. It was working perfectly fine till the time I used to press the backspace. As soon as we press backspace it used to hide the control for some reason.

To overcome this we need to override the default behavior of the “backspace” and “delete” keys.

As shown below I am using the “keydown” event, please do not use KeyPress event as it does not gives the required result

$("#timepickerControl").keydown(function (e) {

            switch (e.keyCode) {

                case 46:  // delete

                    e.preventDefault();

                    alert("Del Key Pressed ,Please use slider to enter valid input");

                    break;

                case 8:  // backspace

                    e.preventDefault();

                    alert("Backspace Key Pressed ,Please use slider to enter valid input");

                    break;

            }

        });
The above code will stop the hiding if I click on the text box provided for the control.
In order to disable the backspace on the complete document and the parent document we need to have two extra pair of functions as below


 // Prevent the backspace key from navigating back on the webresource.

        $(document).unbind('keydown').bind('keydown', function (event) {

            var doPrevent = false;

            if (event.keyCode === 8) {

                var d = event.srcElement || event.target;

                if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

             || d.tagName.toUpperCase() === 'TEXTAREA') {

                    doPrevent = d.readOnly || d.disabled;

                }

                else {

                    doPrevent = true;

                }

            }

 

            if (doPrevent) {

                event.preventDefault();

            }

        });

 

    });

 

    //Prevent the backspace key from navigating back on the parent form containing the webresource.

    $(window.parent.document).unbind('keydown').bind('keydown', function (event) {

        var doPrevent = false;

        if (event.keyCode === 8) {

            var d = event.srcElement || event.target;

            if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD'))

            || d.tagName.toUpperCase() === 'TEXTAREA') {

                doPrevent = d.readOnly || d.disabled;

            }

            else {

                doPrevent = true;

            }

        }

 

        if (doPrevent) {

            event.preventDefault();

        }

    });