Validate Multiple Fields in JavaScript

CRM forms can often have multiple fields marked as business required. Mandatory validation is sometimes even added dynamically via JavaScript, for example based off the value of an option set. If you have a large CRM form, it's not always possible to see all of the red (*) asterisks; users will have to try and save the form over and over to be prompted and receive focus of each missing field individually.

You can instead program all of your business required fields into an array in JavaScript, and present all of the missing information in one popup box. This is more user-friendly.

First, setup your array of fields as objects where each object holds the schema name, label and value of the field:

Then iterate through all of your fields to determine which, if any, don't contain a value (which they should because they're business required):

Note: I've chosen to use Array.prototype.forEach() in this example because it's supported in IE9 and above. If your CRM user base is using a more modern browser, consider using let:

More information on array iteration and JavaScript browser compatibility here.

Anyway, we finally need to format the labels of our fields which are missing information into a readable message to be presented as an alert. The following code splits the array of field labels each with a comma, except the last element where an 'and' is placed:

You can then present your alert with alert(message);:

As an alternate message formatting, you could use the • unicode character and the \n escape character to mock bulletpoints. Unfortunately, html tags can't be passed to alert boxes, otherwise we'd use ul:

Note: the example above only uses three fields. The solution presented should probably only be used for a requirement involving 10+ fields. Adding JavaScript adds complexity to the system and makes it harder to maintain and should therefore be avoided where possible.

No comments:

Post a Comment