Saturday, April 2, 2011

SharePoint 2010: Custom Validation in List Form for US Phone Number

Recently I had hard time in validating the a filed for a phone number in a custom list form. The OOB ASP.NET RegEx validator can be used but somehow in SharePoint 2010 even if the RegEx expression is correct, it does not validate the correctly formated number. Therefore I decided to use the custom validator.

1. Before you go ahead and use the validator, you should have the ID of the control you wish to validate. The best way I have figured out so far is:
    a. Browse to the custom new form in browser and go to view source
    b. Locate the control and copy the portion of the control name (not the ID) aftre the ff value of control. For example if the name of the control is ctl00$m$g_7864a235_2177_4ad9_bb8e_c9c86a8b6b4f$ff61$ctl00$ctl00$TextField then you should copy only the text aftre the ff (form field) text including ff. so the form name that you will use for this example will be ff61$ctl00$ctl00$TextField

2. You can simply insert the custom ASP.NET validator from ASP.NET tools sectionwhile you are in design view of the custom form:

3. Put correct statement in error message property of the validator.
4. Paste this name (ff61$ctl00$ctl00$TextField in our example) in the ControlToValidate property of the custom validator.
5. Put the name of the javascript function (where you will be performing the validation.) in the ClientValidationFunction property of custom validator.
6. Go to the Code of your form and put the java script function in the PlaceHolderAdditionalPageHead area.
Sample Code:

        function ValidateCallerPhoneNumber(source, arguments)
{
var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
arguments.IsValid = phoneNumberPattern.test(arguments.Value);
return;
}


To understand the RegEx, please read this.

And you are all set.On run time, the custom validator will fire this java script function and supply the required parameters and get the IsValid back from function and show the error message in case validation fails.

No comments:

Post a Comment