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>
//lo contacts not assignedprotected 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 gridsprotected void AddValidations(object sender, GridViewRowEventArgs e)
{//find contact typeTextBox 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 validatorif (tbContactType.Text == "EMAIL" || tbIsPhone.Text == "T")
{RegularExpressionValidator rev = (RegularExpressionValidator)e.Row.FindControl("ValidateContactData");//if its a phone add validatorif (tbIsPhone.Text == "T")
{rev.ValidationExpression = "\\(\\d{3}\\) \\d{3}\\-\\d{4}";//add js for the type of contactcontactdata.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;}
}