Monday, November 5, 2012

Show custom error message for validation

We can do validation on item adding event and prevent item to being added in to the list, you can refer to Validating list item when added to the list. After cancelation on insertion of item in to the list it gives ugly message and it is difficult to user comprehend that message.

1. You can add below code to show custom error message.

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}$"))
{
//Custom error message.
string sErrMsg = "Business Phone is not in correct format";
properties.ErrorMessage = sErrMsg;
properties.Cancel = true;
}
}
if (!string.IsNullOrEmpty(sEmail))
{
if (!System.Text.RegularExpressions.Regex.
IsMatch(sEmail, @"^(?("")("".+?"
"@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\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}))$"
))
{
//Custom error message.
string sErrMsg = "Email is not in correct format";
properties.ErrorMessage = sErrMsg;
properties.Cancel = true;
}
}
}



2. Now, it will show custom error message which we have set in code. But still it will show that ugly page. So we can add our own custom error page, isn’t sounds good!!


3. Go to Project and add new Application page and name it as “CustomErrorPage.aspx” as shown in below page.

image

4. Open up the .aspx page and add a label under the section:
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

And change the ID of the label to lblErrMsg and clear out the text parameter.

 


In Page Load method add below code.


protected void Page_Load(object sender, EventArgs e)
{
string sErrMsg = Request.Params["ErrMsg"];
lblErrMsg.Text = sErrMsg;
}



5. Now we will need to add code to get redirected to our custom error page when validation fails. Add below code after line properties.Cancel = true.

properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = string.Format("/_layouts/ListItemEventReceiver/ CustomErrorPage.aspx.aspx?ErrMsg={0}", sErrMsg);



6. Now it’s time to test the solution. Press F5 it will deploy the solution and in browser add invalid entry for email. You will see custom error message as below fig.

image

No comments:

Post a Comment