The new key press event allows all developers to trigger a function when the user presses keys in a number or text control.  This will allow developers to provide more rich data validation in a supported manner which is especially useful if auto-save is used in organizations.

Example, if We want to ensure the user enters valid data into the native phone number field, we can register on the key press event and automatically remove invalid characters as the user presses them.

First we will setup a function on the new addOnKeyPress event for the main telephone field.

Xrm.Page.getControl(‘telephone1’).addOnKeyPress(function() { }); 

Then we will retrieve the value from the main telephone field to get the keys that the user inputted.

var userInput = Xrm.Page.getControl(‘telephone1’).getValue(); 

Then we will build a regex to replace any of the inputted keys that are not “(“, “)”, “-“, or a number.

userInput = userInput.replace(/[^\d-()]+/g, ”);

Lastly, we will replace the main telephone value with the new clean version of the user’s input

Xrm.Page.getAttribute(‘telephone1’).setValue(userInput);

Now if a user presses an invalid character in the main telephone field, it will automatically delete the character so the field will not be saved with invalid data.

Advertisements