Dynamics CRM: client-side validations

The great part of working in a team is that you get to see some nice examples of how other people solve the same old (or, sometimes, new) problems. Take client-side validations in Dynamics CRM.. It’s always the same basic idea: create a javascript function that will be assigned as an event handler for the OnChange/OnSave events. However, most of the examples you will find online are lacking the “universality” – more likely than not, you’ll have to pass attribute name to the function.

However, there are two client-side SDK features which will allow you to create reusable validation logic.

Namely, those are the ability to pass execution context and the ability to set control notifications.

Once you have execution context, you can use getEventSource call to find out Xrm.Page object model that is the source of the event. Which means you don’t need to pass attribute names to your validation scripts, you just need to make sure “execution context” is passed as a parameter when configuring your event handlers.

As for the setNotification, that’s just a nice simple notification mechanism which you can use to stop CRM from saving data when/if your validation fails.

Here is an adopted example of how one of my colleagues implemented javascript validation to ensure that a text CRM field represents a valid year – you just need to create a web resource for this code, attach ValidateYear function as a handler for the field’s OnChange event, and ensure that “pass execution context” option is selected:


function ValidateYear(executionContext) {

  var attribute = executionContext.getEventSource();

  var fieldName = attribute.getName();

  var control = Xrm.Page.getControl(fieldName);

  var yearStr = attribute.getValue();

  if (/^\+?(0|[1-9]\d*)$/.test(yearStr)) {

    if(Number(yearStr) > 1900 && Number(yearStr) < 2100))






  var errorMessage = “You must enter a valid year between 1900 and 2100”;



Posted in Dynamics CRM and tagged .

Leave a Reply

Your email address will not be published. Required fields are marked *