Using an External Script file to add event code to a field.

A customer had the requirement to place some rules on the company name field to discourage users from entering characters that were not allowed in business names.

Which special characters may be used in a business name will differ between countries. I am most familiar with the UK rules having set up and run my own company in the past. If you are British and you are trying to decide on a company name then if can be a useful, if not an entirely enjoyable, experience to read the "The Company and Business Names (Miscellaneous Provisions) Regulations 2009".

Basically the rules I have tried to implement about Company names are that they may...

  • include any alphabetic character including space and ampersand
  • use standard grammatical symbols e.g. full stop, comma, colon, semi-colon or hyphen

To help me with this I used a regular expression. A very useful site to help build the regular expression is http://regexr.com/

I could then add the rule into the CompanyBoxLong and use this script on the onChange script

[code language="javascript"]
re = /[^A-Za-z? &0-9.;:,\-() ]/;
r = this.value.match(re);
if (r) {
crm.infoMessage(crm.getTrans('Errors', 'IllegalChars'));
crm(this.name).background("#fff000");
crm.hideButton('Save.gif');
}
else {
crm.infoMessage(false);
crm(this.name).background(false);
crm.showButton('Save.gif');
}
[/code]

But, the customer didn't want script entered into the system.

So instead I created a script file and added this to the custom script location. I have talked about how to do that in the article "Script Libraries: Reusing Client Side Code Between Screens".

[code language="javascript"]

crm.ready(function () {
//function script goes here
var contextInfo = crm.getArgs();

//add rule when company is in edit mode
if (contextInfo.Act == "201" & & contextInfo.Mode == "3") {
//Add the onchange rule
$("#comp_name").change(function () {
re = /[^A-Za-z? &0-9.;:,\-() ]/;
r = this.value.match(re);
if (r) {
crm.infoMessage(crm.getTrans('Errors', 'IllegalChars'));
crm(this.name).background("#fff000");
crm.hideButton('Save.gif');
}
else {
crm.infoMessage(false);
crm(this.name).background(false);
crm.showButton('Save.gif');
}
});
}
})

[/code]

I have used a little bit of jQuery to add the behaviour to the screen when it is in edit mode.

$("#comp_name").change()

I used the crm.getArgs() method to check the act code and the Mode value to ensure the script was only added in edit mode.

The rule will highlight the field when illegal characters are entered into the company name field. A message will be displayed and the error is pulled via Ajax from the custom_captions table.

Anonymous