As we all know, a SharePoint page can only have one <form > tag in it. As anyone who wanted to use jQuery validation knows, the validation script needs to run on a form tag.
So how do I use the validation code in a sharepoint web part?
The answer is to run the script against the form that already exists in the page. For example, I had to write a web part with an email address field, and wanted to help the users by validating the text they entered is a valid email address on the client side (I also validate on the server side – just in case someone is running a browser with no script). This is the “Render” override code that I used:
txtEmailAddress1.CssClass = “required email”;
if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)
$(""#" + this.Page.Form.ClientID + @""").validate();
As you can see, I am adding a css class of type “required email” for the text box, and then telling the form on the page to validate using the jquery validation plug in. This of course assumes you added the references to the jquery scripts to the page…which you may want to do as part of the web part (override oninit, and registerclientscriptblock) or as part of the master page (if you expect a lot of web parts to use it).
As for the “if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)” line – you have to be careful that your validation does not prevent you from editing the page. For example, if you remove that “if”, you will not be able to change the properties of any web part on the page without first entering a valid email address in the textbox!
Ref : Sharepoint Tips And Tricks
- Go to jquery.com and download the latest jQuery library to your desktop. You want to get the compressed production version, not the development version.
- Open SharePoint Designer (SPD) and connect to the root level of your site’s site collection.
- In SPD, open the “Style Library” folder.
- Create a folder named “Scripts” inside of the Style Library.
- Open your master page file in SPD.
- Within the <head> tag of the master page, add a script reference to the jQuery library just above the content place holder named “PlaceHolderAdditonalPageHead” (and above your custom CSS references, if applicable) as follows:
- Immediately after the jQuery library reference add a script reference to your custom scripts file as follows:
Now, go to your desired page and put the page in edit mode. Add in the Content Editor Web Part located under the Media and Content category. Once added select the web part and use the ribbon UI to navigate to the Web Part Properties screen.