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 ); }
}
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.
9 comment(s)Login first to comment...
jeniffer homes
(at 01:48 on 22.07.2016)
Consider this just a basic framework for putting all your validation in one place.
Don Mottolo
(at 20:16 on 07.05.2015)
Bill, It is actually called by the server event (not the client event), so the validation is running as SSJS. Since it is in the condition section of an Action Group, a true result will run any other SSJS and Simple Actions that you include in the group; or skip them all if the result is false. You're right that this makes it nice for doing additional processing on submitting, for example workflow rules. I like creating a SSJS script library functions and calling them after validation. That way, you can keep your different types of processing in separate libraries and functions for validation, workflow, etc.
Bill Fox
(at 17:50 on 02.01.2015)
So validateForm() is called by the client side, if successful does it then pass it to the SSJS code on the button? This would be really cool because once the validation if completed I need to do several SSJS things.
Right now I use a "Button" not submit because in the SSJS I need to save several dataSources in a very specific order as well as call a LS Agent. Going to convert the LS Agent to JAVA someday but right now the LS works fine.
If this works It should be a great addition. I hate the native XPages validation way to hard to control and as you say you have little bits of code all over the place that comes back to bite you.
Don Mottolo
(at 13:01 on 21.10.2014)
UPDATE: One thing that I recently found that will cause a problem is having a navigation rule for failure, like
<xp:navigationRule outcome="xsp-failure" viewId="/main.xsp">.

If you're having problems getting this to work, be sure to remove any navigation rules for a failure condition.
Don Mottolo
(at 07:52 on 25.09.2014)
Hi Fatih, The code in this snippet only shows a very basic check to see if the field is empty or not, but you can easily modify it to include much more complicated tests (such as Regular Expressions) for testing numbers and dates. Consider this just a basic framework for putting all your validation in one place.
fatih duranoğlu
(at 02:57 on 27.08.2014)
Hi Don

i have problem number field and date field. Code not validate Number or date type component
Don Mottolo
(at 08:55 on 07.06.2013)
There's a little more background info on my original blog post
https://www.bleedyellow.com/blogs/swissarmyknife/entry/xpages_ssjs_form_validation_that_triggers_errormessage_controls?lang=en
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.