Please note that this post is aimed as showing how to use javascript regular expression field level validation in Microsoft Dynamics CRM. The post does not focus on the many ways of getting a regular expression. The example regular expression below is used for explanation only.
If you want to create validation at field level in Microsoft Dynamics CRM 4 to check the input value and text of a CRM field in an entity form, you can do this using regular expressions written in javascript code that handles the on change (onChange) event of this field at client side.
Below is an example of a regular expression but you might want to use your own regex value or search online for almost unlimited number of regular expressions that do just about anything.
For example, if you want to validate a CRM 4 field so that only a 4 digit year value starting from year 1980 is entered in the field text box, follow the following steps:
- Open the entity customisation form
- select the field you want to validate using javascript regular expression.
- Click on field properties, events tab and then open the onChange event.
- In the onChange event type the following javascript code (script) to handle the event and implement the field level validation:
//-----------------------------
//Regular expression ensuring a 4 digit year value is input starting from year 1980.
var reDate =/^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$/
//Check if the input value satisfies the regular expression condition
if (document.crmForm.all.new_yearfieldname.value.search(reDate)==-1)
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------
Another way of doing this is as follows;
//-----------------------------
var regexS = "^(([1]{1}[9]{1}[8-9]{1}\d{1})|([2-9]{1}\d{3}))$";
var regex = new RegExp( regexS );
var results = regex.exec( crmForm.all.new_yearfieldname.value);
if( results == null )
{//if match failed
alert("Please enter a valid year value. Year value must be four digits starting from the year 1980")
crmForm.all.new_yearfieldname.value = '';
}
//-----------------------------
Hope this helps.