In this recipe we will be looking at how to handle unexpected user input. While this is already in place for some specific field types, we can easily enhance the system functionality through very simple validation scripts and user feedback messages.
Using one of the previously created solutions or creating a new solution, add the Contact entity to the solution. We will focus our attention on the Contact fields, but the same code can be applied to any standard or custom entities created in Dynamics CRM.
Some standard field formats in CRM include elements of user input validation. Upon data entry, users are prompted if their input is invalid, and the focus returns to the field, while the incorrect input is cleared. Take the date field as an example. Enter in a date field a string of abc123
to observe the behavior. The following prompt gets displayed:
Once you click on OK, your input is cleared, and the focus is returned to the field you were trying to modify. But let's see how we can achieve the same result on a standard text field. We want to check that the input starts with a capital letter, is longer than three characters, and does not contain spaces. If these requirements are not met, we'll bring up a notification message, clear the field, and return the focus to it.
In order to test our script, we'll create a new text field. Perform the following steps to do so:
new_SingleName
). Set it to type single line of text, format of text, and a maximum length of 100.new_JSUserInput
.function CheckUserInput() { var _userInput = Xrm.Page.getAttribute("new_singlename").getValue(); var _isValid= false; if(_userInput != null && _userInput != "") { if(_userInput.match(/^[A-Z][a-z]+$/)) { _isValid= true; } } if(_isValid== false) { // clear the field _userInput = ""; Xrm.Page.getAttribute("new_singlename").setValue(_userInput); // alert alert("The input is not valid!"); // set focus Xrm.Page.getControl("firstname").setFocus(true); Xrm.Page.getControl("new_singlename").setFocus(true); } }
OnChange
event of the Single Name field we created.There are two parts of this function, as follows:
You have probably observed that I have set the focus twice, first to the First Name field, and second time back to our field. The first time when you set the focus, you can use any field on the form. The reason for doing that is, if you set the focus directly on your custom field, it will not work. Back in Dynamics CRM Version 4 a hotfix was released to address this issue. You can find out more information at the following URL:
Using regular expressions is a very handy way of validating user input. I suggest you pay close attention to the regular expression syntax. For additional details, a good starting point is w3schools at http://www.w3schools.com/jsref/jsref_obj_regexp.asp.
The following URLs can be referred to for further information:
SetFocus
functionality in Dynamics CRM 4.0 available at http://support.microsoft.com/?scid=kb;en-us;953291&x=10&y=418.219.111.195