Thursday, February 4, 2016

Keypress methods in CRM2016

CRM2016 introduced the new keypress methods for text and numeric fields to support keypress events on CRM forms. These methods will be useful to provide immediate feedback on key press. Traditionally, all the validations and actions were executed via the “on Change” event. These methods include
  • addOnKeyPress
Use this method to attach an event handler to the keypress event
  • removeOnKeyPress
Use this method to remove an event handler to the keypress event
  • removeOnKeyPress
Use this method to manually fire an event handler to the keypress event
For this blog, I have created sample code that will stop the input of numbers in the name field of the account record.
Here are the steps
  1. Create a new JScript web resource and add the following code to it.

     // JavaScript source code  
     function keyPress()  
     {  
       //attach the validateInput function to the keypress event of the name attribute  
       Xrm.Page.getControl("name").addOnKeyPress(validateInput);    
     }  
     function validateInput() {  
       //get the value of the name field  
       var input = Xrm.Page.getControl("name").getValue();  
       if (input != "") {  
         //check if the last key pressed is a number  
         if (isNaN(input.substr(input.length - 1)) == false) {  
           //display the message  
           alert("Numeric values are not allowed in the account name");  
         }  
       }  
     }  
    

  2. Save and publish the web resource.
  3. Open the account form in customization mode.
  4. Add the JScript web resource to the form and call the keypress() method from load.
  5. Save and publish the account form.
  6. Test the code. If you try to press a number key on the name field you will get an error message as shown in the following screenshot.