Adding Events to SharePoint Fields

SharePoint Logo[This article should be considered deprecated.  The code represented has been improved, extended and made available as the DP_SharePoint Function Library.  All future effort will be applied there.]

The first article in this series dealt with obtaining a reference to a SharePoint field in Add and Edit forms.  One of the most common reasons to head down this path is to add custom validation to fields.  Often this requires adding events to (in the case of most fields) the onchange or (in the case of buttons) the onclick events of the fields.  Simply setting the event handler directly would work, but will eliminate any currently enabled handlers (such as those defined internally to SharePoint).

Instead I created two functions to abstract the standardized addEventListener() and (for older IE browsers) the attachEvent() methods.  They accept a reference to an HTML element (in this case a SharePoint form field), an event type and a function name to call when the event is fired.  The first adds an event to the passed element and the second (which is included for balance but which I’ve honestly never actually used) removes it.

	// addFieldEvent Method
addFieldEvent = function( Field, Event, Handler ) {
	if (Field.addEventListener) {
		Field.addEventListener(Event, Handler, false);
	} else if (Field.attachEvent) {
		Field.attachEvent("on" + Event, Handler);
	};
};
	// removeFieldEvent Method
removeFieldEvent = function( Field, Event, Handler ) {
	if (Field.removeEventListener) {
		Field.removeEventListener(Event, Handler, false);
	} else if (Field.detachEvent) {
		Field.detachEvent("on" + Event, Handler);
	};
};

The “Field” reference can be retrieved from the getFieldRef() function in the first article.  “Event” is any standard HTML event but most often common form field events like “click”, “change”, etc.  Finally the “Handler” is the name of a function (without parenthesis as we’re passing a reference to the function rather than running it) that will be triggered whenever the event is triggered.

Note that using this more standardized method for managing events means that you can added multiple events to a single element.  However the order of operations (the order in which the handlers are called) is not predictable and, for purposes of discussion should be considered random.

SharePoint Support Functions

SharePoint provides two functions that are invaluable to this kind of work and that we’ll be using in our example below.

The first is PreSaveAction().  You will create this function if needed.  If present this function is called when the submit button is called on an Add or Edit form.  If the function returns “false” the form will not be submitted, if it returns “true” it will submit as normal.  Although we’ll be adding instant validation to our fields in our example repeating that validation in PreSaveAction() ensures that the user has taken corrective action.

The second is _spBodyOnLoadFunctionNames.push() and it accepts a function name as input.  This function is automatically loaded and available for use on any SharePoint form.  Similar to our event functions this function allows you to add multiple new functions to the onLoad event handler of a SharePoint form without affecting other functions waiting to load.

An Example

Consider a SharePoint List with two columns, “Minimum” and “Maximum”.  Your business rules are as follows:

  • The fields are numeric and default to “1” and “10” respectively.
  • Values can’t be less than “1” or greater than “10”.
  • “Minimum” must be less than “Maximum”.

Using the functions we’ve described so far we’ll create two functions: the first will be run when the form loads and will add events to the fields (on the “change” event specifically) and the second will be handler for that event.  It will test the business rules and provide an alert if any of them are violated.

(To save space the getFieldRef() and the addFieldEvent() functions are assumed to be present but not included in the sample code.)

	// Manage all custom validation
function CustomValidation() {

		// Get Field References
	var MinFld = getFieldRef("Minimum");
	var MaxFld = getFieldRef("Maximum");

		// Add Custom Validation
	addFieldEvent(MinFld, "change", CustomVal_MinMax_Change);
	addFieldEvent(MaxFld, "change", CustomVal_MinMax_Change);

};

	// Manage checks on submit
function PreSaveAction() {

		// Run submit-level validation
	if ( !CustomVal_MinMax_Change() ) { return false };

		// Return true (success)
	return true;

};

	// Validation for Min and Max
function CustomVal_MinMax_Change() {

		// Get Field References
	var MinFld = getFieldRef("Minimum");
	var MaxFld = getFieldRef("Maximum");

		// Get Current Values
	var CurMin = MinFld.value;
	var CurMax = MaxFld.value;

		// Check Rules
		// Any failed checks return "false" to support PreSaveAction()

		// Numeric
	if ( typeof CurMin != "number" ) {
		alert("The value of Minimum must be a number");
		return false;
	};
	if ( typeof CurMax != "number" ) {
		alert("The value of Maximum must be a number");
		return false;
	};

		// Value Range
	if ( CurMin < 1 || CurMin > 10 ) {
		alert("The value of Minimum must be between 1 and 10");
		return false;
	};
	if ( CurMax < 1 || CurMax > 10 ) {
		alert("The value of Maximum must be between 1 and 10");
		return false;
	};

		// Min must be less than Max
	if ( CurMin >= CurMax  ) {
		alert("The value of Minimum must be less than Maximum");
		return false;
	};

		// Return true (success) to support PreSaveAction()
	return true;

};

	// Add the CustomValidation to the call stack
_spBodyOnLoadFunctionNames.push("CustomValidation");

Note how the validation function CustomVal_MinMax_Change supports both the change-based validation (by providing instant feedback) and the PreSaveAction() validation (by returning false if any of the validation rules are violated).

Any additional validation for the form can be configured in CustomValidation(), given their own custom handlers and those handlers can be added to PreSaveAction().  As noted previously in most cases this code will need to be added to both the Add and Edit forms to cover all cases.

In the next entry I’ll cover some techniques for making more drastic changes to SharePoint forms.

1 Comment

Add a Comment

Leave a Reply