Wednesday, March 09, 2011

CRM 2011 - Phone Format Validation using JavaScript and Regex

Reusing JavaScript functions in CRM 4.0 was not easy and many people simply copied the code from one form or field to another so they ended up with lots of duplicated code.

Dynamics CRM 2011 introduced the concept of web resources which are files of reusable resources. In this example I am going to create a JavaScript library as a web resource file to hold a function which validates the format of a mobile phone number using a regular expression. Under customization create a new resource file of type JavaScript.

Add caption


Click on Text Editor and add the following JavaScript to the source

function validateMobile(context)
var mobi =context.getEventSource().getValue();
mobiRegex = /^(083|084|085|086|087|088|089)\s?\d{3}\s?\d{4,5}$/;
if( !mobi.match( mobiRegex ) )
   {
   event.returnValue = false;
   alert("The format of the mobile no is incorrect") ;
   }
}

Customize the main form of the Contact entity and click on the Form Properties and add the new resource file we created as a library. It can now be used in the form

Click on the mobile number field to hook up the onChange event to our newly created validation function. Under the event tab add a new event handler as shown. Make sure you check the “Pass execution context as first parameter” so that we can access the field context in the Javascript function. Save the form and publish the Contact entity.


Now on the contact form when the mobile number is changed the validateMobile function will be fired and because we are using a web resource file we can reuse it throughout the solution.







1 comment:

  1. I think we need to reset the field value to empty, if regular expression match fails

    function validateMobile(context) {
    var mobi = context.getEventSource().getValue();
    mobiRegex = /^(083|084|085|086|087|088|089)\s?\d{3}\s?\d{4,5}$/;
    if (!mobi.match(mobiRegex)) {
    context.getEventSource().setValue('');
    event.returnValue = false;
    alert("The format of the mobile no is incorrect");
    }
    }
    }

    ReplyDelete