Monday, October 11, 2010

Apply Validation using Javascript in Sharepoint


1. Add the CEWP on the EditForm or Newform.aspx
2. Paste Below script in that and change the types and respective Control names
3. To pass correct parameter in the "TagName" function follow
TAGNAME: HTML element that is being rendered ("SELECT", "INPUT"...)
IDENTIFIER: SharePoint field type identifier ("TextField", "DropDownChoice"...)
FIELD NAME: Display name of the field (e.g. "Status", "Customer Name"...)



function PreSaveAction()
{
var Email = TagName("INPUT","TextField","Customer Email Id");
var result=checkEmail(Email.value);
if(result== "0")
{
alert("Please enter proper Email address");
return false; // Cancel the item save process
}
return true;

}
function TagName(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;
}
function checkEmail(inputvalue){
var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(pattern.test(inputvalue)){
return 1;
}else{
return 0;
}
}

1 comment:

Anonymous said...

This is perfect. Thanks. I was wondering if you no how to add the ability to check only if the field is populated. In other words, this field isn't required for me, so I don't need a popup unless someone fills out the email field and its invalid. Any help would be appreciated.

Regards,
Ink