Thursday, 30 January 2014

CRM 2011: How do I validate that a text field is numeric?

I need to change the format of an ID field in CRM 2011. The system settings were inserting commas as thousands separators and this looks strange for an ID (ID 123,456 is just not right).

I recreated the field as a text field, but I needed to validate the input.I therefore created the following functions that I added to the 'onSave' list of my CRM form:

When configuring the script, ensure that 'pass context as the first parameter' is set and then pass in the name of the field to search (in double quotes).

Here is the script:

validateIDOnSave = function(executionObj, IDField)
{
    var IDFieldValue = Xrm.Page.getAttribute(IDField).getValue();

    if(IDFieldValue != null)
    {
      var IDFieldObject = Xrm.Page.ui.controls.get(IDField);

      if (isNumber(IDFieldValue ) == false)
       {
                executionObj.getEventArgs().preventDefault();
                alert("The ID must be a number");
                IDFieldObject.setFocus();
        }
    }
    else
    {
        // ID Field is null. Don't validate
    }
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

No comments:

Post a comment