Search This Blog

Thursday, December 9, 2010

SharePoint 2007 Form Validation Using JavaScript

1. From time to time a customer asks for validation on the SharePoint EditForm.aspx or NewForm.aspx. While there are many types of form validation that can be done, one of the most versatile and effective is validation using the Content Editor Web Part and JavaScript. In this article I will guide you through configuring and developing this kind of validation.

2. Here is our scenario; we need to add validation to a custom task form so that when the user edits the task form and reassigns the task he is prompted to provide a reason for the reassignment. Our custom task form will have a customized Task Status field and an additional custom field, Reassignment Reason, as shown below:

a. Task Status (Choice)

i. Assigned
ii. In Progress
iii. Completed
iv. Reassign

b. Reassignment Reason (Multiple Lines of Text)

3. So the first question you may be asking is “How do I add a CEWP to the Edit and New forms?” I’m glad you asked! While the New and Edit forms do not provide an interface to access to the Edit Page function in the Site Actions menu, you can still get access to this capability through the browser by appending the following query to the end of the URL string for the New and Edit forms:

&pageview=shared&toolpaneview=2

4. OK, so now that you can see the Edit Page interface of the Task Form lets add a CEWP in the usual way, just click on the “Add a Web Part” control at the top of the Web Part Zone and then from the Webpage Dialogue scroll down to the Miscellaneous section and choose Content Editor Web Part. Now click on the Add button at the bottom of the dialogue page and the CEWP will be added to the page.

5. Now click on the edit button of the CEWP in the Web Part Zone and choose the menu option “Modify Shared Web Part”. This will bring up the web part configuration interface in the right panel. From this interface click on the Source Editor and the text entry dialogue box will open. This is the area where you will need to write your code. We aren’t going to write any code right now though, so you can close the dialogue box.

6. Now we have to talk about the special JavaScript function we will need to use in order to “discover” the SharePoint controls in the task edit page – this function is called “getTagFromIdentifierAndTitle” and it is displayed below:

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" ||
tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}}
return null;
}

7. According to Microsoft this JavaScript function “parses the page’s query string, locates the HTML objects that are rendered by the relevant SharePoint fields, and sets their value.” The function can identify the fields by matching three parameters:

a. tagName – The name of the tag rendered in the form’s HTML

b. identifier – The string associated with the SharePoint type of the relevant field

c. title – The value of the relevant HTML tag’s “title” attribute, which also matches the field’s display name

8. While the title parameter is easy to obtain, one of the challenges you will often face when using this script is finding the tagName and identifier parameters. Microsoft provides a partial list as a starting point - see this tech net article: http://blogs.msdn.com/b/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx

9. However, there is another way to find this information, by using a very handy tool set that comes installed with Internet Explorer 8, and which Microsoft has very cleverly named “Developer Tools”. To activate the Developer Tools in IE, press F12 or use the "Tools" – "Developer Tools" menu. To find out more information about any element, click on the “Select Element” arrow in the tool set, and then select the element on the page. The tool set will take you to that elements markup and code and provide a great deal of information about that element to include the identifier and tag name. (If you don’t have the option of updating IE to 8 or higher, with IE7 you can use Developer Toolbar for Internet Explorer.)

10. OK, so now we need to create our function to validate the form when the user commits the change. Here is our basic function outline:

function PreSaveAction() {
//*** Script Variables ***
//Drop Down List Task Status
var theInputDDLTS = getTagFromIdentifierAndTitle("select","DropDownChoice","Task Status");
//Multi-Line Text Reassignment Reason
var theInputMLTRR = getTagFromIdentifierAndTitle("TextArea","TextField","Reassignment Reason");
if(theInputDDLTS.value == "Reassign")
{
if(theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == "")
{
alert("When the Task Status field's value is set to Reassign you must fill in the Reassignment Reason text box. Please either fill in the Reassignment Reason text box or change the value of the Task Status field.");
return false;
}
else
{
return true;
}} }

a. The PreSaveAction() – This is a built in SharePoint function that will allow you to perform validation without PostBack. This will be very useful to us because we want to catch the user’s errors before the form is saved.

b. Script Variables – We need to set two variables, one for the Drop Down List Task Status, and the other for the Multi-Line Text Reassignment Reason. Both of these variables will be set using the getTagFromIdentifierAndTitle function.

c. Nested If Statements – The first “if” statement checks to see if the user selected the task status “reassign”, the second “if” statement checks to see if the Reassignment Reason field is empty (which can represent several different HTML configurations).

d. Both Conditions True - If both conditions are true then the script will execute an alert message informing the using that he must provide a reassignment reason, it then returns false which prevents the form from saving.

e. Only the first Condition is True – If only the first condition is true then that means the user selected the status “reassign” and also provided a reassignment reason, and so the function returns “true” allowing the form to save.

11. OK, all we have to do now is copy our script into the CEWP, so let’s go back to the web part configuration interface in the right panel. From this interface click on the Source Editor and the text entry dialogue box will open. Now just copy and paste the code below into the text box and click “Save” which will close the dialogue box. From the right panel interface click “OK” and then from the EditForm.aspx click OK again, and your form is ready to test.

function PreSaveAction() {
//*** Script Variables ***
//Drop Down List Task Status
var theInputDDLTS = getTagFromIdentifierAndTitle("select","DropDownChoice","Task Status");
//Multi-Line Text Reassignment Reason
var theInputMLTRR = getTagFromIdentifierAndTitle("TextArea","TextField","Reassignment Reason");
if(theInputDDLTS.value == "Reassign")
{
if(theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == ""
theInputMLTRR.value == "")
{
alert("When the Task Status field's value is set to Reassign you must fill in the Reassignment Reason text box. Please either fill in the Reassignment Reason text box or change the value of the Task Status field.");
return false;
}
else
{
return true;
}}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" ||
tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}}
return null;
}}

12. There are other ways to do this type of validation, such as using the returnObjById(id) function, but for whatever reason, Microsoft doesn’t recommend using this approach. On the other hand, in the SharePoint Community the getTagFromIdentifierAndTitle function is well known, well documented, and heavily used, so I recommend starting with this method whenever possible.

I hope that helps!

8 comments:

Anonymous said...

This was very Helpful !

Thanks a lottttttt ... It saved me from my client :)

Tom Molskow said...

I'm glad I could help!

Tom

Anonymous said...

Very new to all of this and followed your steps...but on the new item form the CEWP just displays the code and nothing seems to work. Do i need something else to get javascript client side validation to work on SharePoint new item forms?

Tom Molskow said...

Hello,

Be sure that you are in the Source Editor when you add the JavaScript to the CEWP. Please check this and LMK what you find.

Thanks!

Tom

Darren said...

Was having problems for a while because your code above is missing the 2 ||s following if (tags[i].title == title && (identifier == ""

e.g.

if (tags[i].title == title && (identifier == "" ||

Tom Molskow said...

Hey Darren,

Thanks for letting me know about that, I have corrected the code in both locations.

Thanks!

Tom

cris said...

getTagFromIdentifierAndTitle("TextArea","TextField","Description")

How can I detect if Description is empty ..nothing write inside?

Tom Molskow said...

Hey Cris,

The property tags[i].title contains the value of the description, just check that for an empty string.

I hope that helps!

Tom