Client Side validation in SharePoint New and Edit forms using PreSaveAction() and Javascript Client Object model

It’s very common to validate data before adding or editing item using sharepoint list forms i.e. Newform.aspx and Editform.aspx. To handle this kind of scenario “PreSaveAction()” javascript function can be very handy. The default ‘Save’ button in SharePoint calls this function before it does anything else.

Simply place a Content Editor Webpart in NewForm.aspx or EditForm.aspx. Inside this webpart add this javascript code to do any client side validation –

<script type=”text/javascript”>
function PreSaveAction() {
//Do some validation here
// If valid
//return true;
//else
//alert(‘Some message’);
//return false;
}
</script>

Taking it further, lets implement this in a scenario where I want to stop users from adding items into the list if item count in that list is already 50. In real life scenario, this can be used to implement a system which only allows 50 people to register for some event. The solution will be a combination of –

PreSaveAction – which is a one stop shop which allows me to write a validation logic.
Javascript CSOM – validation logic written in javascript which will use Javascript CSOM to read current item count in the list.

var clientContext = null;
var web = null;
var list = null;
var listItems = null;

function PreSaveAction() {
clientContext = new SP.ClientContext.get_current();
web = this.clientContext.get_web();
list = web.get_lists().getByTitle(“YourListName”);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(“”);
this.listItems = list.getItems(camlQuery);
clientContext.load(list);
clientContext.load(web);
clientContext.load(listItems);
var callback = clientContext.executeQueryAsync(Function.createDelegate(this, function(){ _returnParam= onQuerySucceeded();}),Function.createDelegate(this, function(){ _returnParam = onQueryFailed();}));
}

function onQuerySucceeded(sender, args)
{
var count = list.get_itemCount();
if(count >= 50)
{
alert(‘Registration is closed. Try again next year.’);
var redirectUrl = window.location.protocol + ‘//’ + window.location.host + list.get_defaultViewUrl();
var button = $(“input[id$=GoBack]”);
var elementName = button.attr(“name”);
//Cancel item adding
STSNavigate(redirectUrl);return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(elementName, ”, true, ”, ”, false, true));
}
else
{
//Add item
var button = $(“input[id$=SaveItem]”);
var elementName = button.attr(“name”);
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(elementName, ”, true, ”, ”, false, true));
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(elementName, ”, true, ”, ”, false, true));
}
}

function onQueryFailed(sender, args) {
alert(‘Query failed’);
return false;
}

Trackbacks

Leave a Comment

Your email address will not be published. Required fields are marked *