Saturday, November 3, 2012

Validating list item when added to the list

Many times we need to validate data before adding data or item to the list and notify user with message. We will validate the data for contact list on item adding weather email address and phone no are in correct format or not. The phone number should be of U.S. format. It must consist of three numeric characters, optionally enclosed in parenthesis, followed by a set of three numeric characters, and a set of four numeric characters. E-mail should follow standard email notation. We will not allow user to enter any garbage data. If any of the field do not validates it will not get added in the list and user will get error message.
Here we go…
1. Create contact list in SharePoint.
2. Open visual studio with run as administrator->Select event receiver template and give a name ListItemEventReceiver->select List Item Events->Select Contacts list as event source as shown in below fig->click finish. clip_image002
3. It will create different folder in project. Add below code to the ItemAdding method for validating e-mail address and phone no. If it is not validated then it cancels that event and do not add item to the list.
public class EventReceiver1 : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
           string sWorkPhone = properties.AfterProperties["WorkPhone"].ToString();
           string sEmail = properties.AfterProperties["Email"].ToString();
           if (!string.IsNullOrEmpty(sWorkPhone))
           {
      if (!System.Text.RegularExpressions.Regex.IsMatch(sWorkPhone, @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"))
               {
                   properties.Cancel = true;
               }
           }
           if (!string.IsNullOrEmpty(sEmail))
           {
     if (!System.Text.RegularExpressions.Regex.IsMatch(sEmail, @"^(?("")("".+?""@)|(([0-9a-zAZ]((\.(?!\.))|
[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|
(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zAZ]{2,6}))$"))
               {
                   properties.Cancel = true;
               }
           }
       }
    }
}


4. Now if you add any entry which invalid for email address or phone no you will get following error.

clip_image004
5. Error shown above is default error page of SharePoint but you can show your own custom error page. Show custom error message for validation





No comments:

Post a Comment