Monday, February 28, 2011

Adding Validation in a GridView

I’m doing two things in this example. Adding a javascript to force only certain keys allow during data entry, and adding a regular expression validator.  Depending on the type of data I have, I need a different validator for each row in the grid (or none).
First: setup your validator in your grid template:
<asp:TemplateField HeaderText="Contact Data">
<ItemTemplate>                   
<asp:TextBox  id="contactdata" Text="" runat="server"  /> 
<asp:RegularExpressionValidator ID="ValidateContactData" SetFocusOnError="true" 
runat="server"  CssClass="formerrorsmall"  
ErrorMessage="Invalid format! " 
ControlToValidate="contactdata" />    
</ItemTemplate> 
</asp:TemplateField> 
The method is called from the row data bound for the gridview but it could go into the row data bound method itself –I was just reusing it across multiple row data bounds!
//lo contacts not assigned
protected void gvLOContactsNotAssigned_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{   
AddValidations(sender, e);
}
….

//add the validation expressions and javascripts
//use a method b/c we'll use this for both contact grids
protected void AddValidations(object sender, GridViewRowEventArgs e)
{
//find contact type
TextBox tbContactType = (TextBox)e.Row.FindControl("ContactType");
TextBox contactdata = (TextBox)e.Row.FindControl("contactdata");
//is this a phone?
TextBox tbIsPhone = (TextBox)e.Row.FindControl("IsPhone");
 
//if it's an email or a phone - add validator
if (tbContactType.Text == "EMAIL" || tbIsPhone.Text == "T")
{
RegularExpressionValidator rev = (RegularExpressionValidator)e.Row.FindControl("ValidateContactData");
 
//if its a phone add validator
if (tbIsPhone.Text == "T")
{
rev.ValidationExpression = "\\(\\d{3}\\) \\d{3}\\-\\d{4}";
//add js for the type of contact
contactdata.Attributes.Add("onKeyPress", "return PhoneOnly(this, event); ");
 
}
else if (tbContactType.Text == "EMAIL")
{
rev.ValidationExpression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
}
}
 
if (tbContactType.Text == "CONTACT") //it's required
{
Label lblRequired = (Label)e.Row.FindControl("lblContactRequired");
lblRequired.Visible = true;
}
}

No comments:

Post a Comment