SSJS Form Validation That Triggers ErrorMessage Controls
// This SSJS script library consolidates all the validation in one place
// The postValidationError() function flags a control as invalid and provides an error message
// so that the XPages ErrorMessage control is used to display the error on the page.

var validateForm = function(){
	var valid = true;
	var control;
	var val;
	

	// ***  REPEAT THE FOLLOWING BLOCK OF CODE FOR EACH CONTROL FOR BASIC "REQUIRED" VALIDATION

	// For each field, change the Control Name in getComponent() and the error message text in postValidationError()
	//   Optionally, modify the IF conditions with more complex JavaScript for value ranges, regular expressions, data lookups, etc.

	control = getComponent("title1");
	val = control.getValue();
	if (isEmpty(val)){
		valid = false;
		postValidationError(control,"Please enter a Title");
	}		

	// *** ----------------------------------------------------------------   ***	




	return valid;
}

function postValidationError(control, msg) {
    if ((typeof msg) != "string")
            return;
    var msgObj = new javax.faces.application.FacesMessage(javax.faces.application.FacesMessage.SEVERITY_ERROR, msg, msg);
    facesContext.addMessage(control.getClientId(facesContext), msgObj);
    control.setValid(false);
}

function isEmpty(o){
	return (o == null || @Trim($A(o)[0]) == "" ) ? true : false;
}

function $A( object ){
	try {
		if( typeof object === 'undefined' || object === null ){ return []; }
		if( typeof object === 'string' ){ return [ object ]; }
		if( typeof object.toArray !== 'undefined' ){return object.toArray();}
		if( object.constructor === Array ){ return object; }  
		return [ object ];
	} catch( e ) { Debug.exceptionToPage( e ); }
}





Using the built in validation on XPages controls has the disadvantage that the validation logic gets scattered all over the XPage source.   While the other option of using SSJS for form validation does keep all the code in one place, but presents the problem of how to display the error messages back to the user.    This is the best way I've found so far to keep the code in  one place for maintainability, while using my preferred method of displaying errors to the user right next to the field that they need to fix.   

Credit goes to Matt White for how to call validation in SSJS script library, to Andre Girrard for how to trigger the ErrorMessage control ( postValidationError() ), and to Tommy Valand for the $A() helper function, which allows my simple isEmpty() function to work properly with both single and multi-value fields.  The following technique pulls all those together.


1.  Create the SSJS script library  "xpValidation" using the code snippet.
2.  Add the  "xpValidation" SSJS script library as a resource to the XPage.
3.  Make the submit button's  "Button Type" =  "Button"   (not "Submit")
4.  In the button's OnClick event, click the "Add Group..." button, in the condition, call the validation function:  validateForm()
5.  Then inside the group, add a new "Save Data Sources" Simple Action   and set the "Name of page to open next" (This will only execute if the validation is passed.)

JavaScript (Server)
Don Mottolo
Rating
121

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.







2 comment(s)Login first to comment...
Bruce E Stemplewski
(at 14:27 on 05.03.2012)
This does not seem to be working for me. I have An error message control linked to the field being tested. I also have an error messages control on the xPage.

The save of the document does indeed abort if the validation fails but no error message is ever displayed. Any idea of what the issue is?
Jozsef Lehocz
(at 06:32 on 01.03.2012)
Hello,

Does anyone have experience the following JVM warning on the Domino server console:

"HTTP JVM: WARNING: XPages server validation errors haven't been displayed to the user"

This message is appeared on the domino server console, when the xpValidation functions are called and there are some mandatory fields on the xpaged without data entered in.

The xpages contains error message controls and error messages control as well. In addition the button has a Save Document action, and the function is called from the QuerySave Event of the data source Domino document.

Any suggestions are very appreciated.