Tuesday, September 18, 2012

Sharepoint 2010 - Client Validation of a Custom Form with Javascript

What to do if you want to perform a client validation with Javascript, in your custom new/edit form.

The submit button cames with this code in onclick event:


if (!PreSaveItem()_) return false;WebForm_DoPostBackWithOptions(new ...

The PreSaveItem function invokes PreSaveAction function that you can override with your own definition.If PreSaveAction returns true, then form proceeds to save data, otherwise, it stops with alert.


With Sharepoint Designer 2010, open form with Edit in Advanced Mode and insert code below:


<!-- call jquery -->
<script type="text/javascript" src="/SiteAssets/js/jquery.min.js"></script>
<!-- override PreSaveAction -->
<script type="text/javascript">
function PreSaveAction()
   var field_to_validate = $("select[title='TITLE OF FIELD']").val();
   if(field_to_validate == ""){
     alert("Warning: complete field_to_validate!");
     return false;
   }
   return true;
}
</script>

We add jquery (but if you want to use simple javascript, you can).
Then, check field by title: in browser, input tag came with attribute "Title" equals to display name of column, then I search for this value.
If empty, return alert then false.