Wednesday, January 20, 2010

Simple Input Validation through HTML Attributes

The best place to validate user input is at the source. If you can keep field validations in the browser, you can avoid unnecessary server requests and provide immediate user feedback while reducing the amount of bad data being submitted. This can be especially useful in the standard interactivity client because it can perform validations immediately, without waiting for the user to attempt to commit the record.

A Siebel form applet is an HTML form, and the controls are input elements on those forms. The HTML Attributes property of a Control object provides an opportunity to insert a JavaScript event to the input element.

For example, I recently implemented a query applet with a field validation on the Social Security Number control. To do so, I updated the HTML Attributes property of the control to

onkeyUp="if(/[^0-9\-]/.test(this.value) ){ alert('The Social Security Number field accepts only numeric data.'); this.value='';}"

The above validation intercepts the onkeyUp event of the input element, and uses a regular expression test to detect if the key pressed was any other besides a number or a hyphen. If an errant character is found, the applet displays a message and clears the control. This validation occurs entirely on the browser, but without adding any browser scripts to the applet.

Here's another example of a date validation on another control on the same applet:

onBlur="if(/^( *)((0[1-9]|[1-9]|1[012])[/](0[1-9]|[1-9]|[12][0-9]|3[01])[/](18|19|20)\d\d)( *)$/.test(this.value)||this.value==''){}else{alert('The Date of Birth field accepts date input in the M/D/YYYY or MM/DD/YYYY format');this.value='';}"

A somewhat more complex regular expression tests the format of a date. In this case, the expression doesn't test the input until the focus moves out of the field.

The HTML Attributes property of the Control object provides a clean, declarative approach for input validation.