Set ASP.Net RegularExpression Validator Expression based on DropDownList using C# and VB.Net

Last Reply 24 days ago By pandeyism

Posted 24 days ago

I have a regular expression  like below what my goal when user changed dropdown country in that  ddl country selected index depending on the country i have set

But my problem is when there is no VatRegularExpression value. for example when i select country germany there is no regular expression for this country.then also still it is giving the error message but it should not give the error message.Can you help me out please

VatRegularExpression = sp.CountryVatRegularExpressionGet(ddlCountry.SelectedValue)  ---here i  am getting regular expression from database

If Not String.IsNullOrEmpty(VatRegularExpression) Then
    RegtxtVatCode.Enabled = True
    RegtxtVatCode.ValidationExpression = VatRegularExpression
End If

 

<asp:RegularExpressionValidator ID="RegtxtVatCode" Enabled="false"
    runat="server" ControlToValidate="txtVatCode" Display="Dynamic" CssClass="help-block"
    ErrorMessage="<%$ Resources: res, WrongVatCode %>">
</asp:RegularExpressionValidator>

 

Posted 24 days ago

Hey rakibxl,

Please refer below smaple.

HTML

<asp:DropDownList runat="server" ID="ddlCountry" OnSelectedIndexChanged="Select">
    <asp:ListItem Text="Select" />
    <asp:ListItem Text="India" />
    <asp:ListItem Text="USA" />
    <asp:ListItem Text="UK" />
    <asp:ListItem Text="australia" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtVatCode" />
<asp:RegularExpressionValidator ID="RegtxtVatCode" Enabled="false" runat="server"
    ControlToValidate="txtVatCode" Display="Dynamic" CssClass="help-block" ErrorMessage="WrongVatCode">
</asp:RegularExpressionValidator>
<asp:Button Text="Validate" runat="server" OnClick="Validate" CausesValidation="false" />

Code

C#

string VatRegularExpression = "";
protected void Select(object sender, EventArgs e)
{
    if (ddlCountry.SelectedIndex > 2)
    {
        VatRegularExpression = "^[I-T]";
    }
}

protected void Validate(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(VatRegularExpression))
    {
        RegtxtVatCode.Enabled = true;
        RegtxtVatCode.ValidationExpression = VatRegularExpression;
    }
    else
    {
        RegtxtVatCode.Enabled = false;
        RegtxtVatCode.ValidationExpression = VatRegularExpression;
    }
}

VB.Net

Private VatRegularExpression As String = ""
Protected Sub [Select](ByVal sender As Object, ByVal e As EventArgs)
    If ddlCountry.SelectedIndex > 2 Then
        VatRegularExpression = "^[I-T]"
    End If
End Sub
Protected Sub Validate(ByVal sender As Object, ByVal e As EventArgs)
    If Not String.IsNullOrEmpty(VatRegularExpression) Then
        RegtxtVatCode.Enabled = True
        RegtxtVatCode.ValidationExpression = VatRegularExpression
    Else
        RegtxtVatCode.Enabled = False
        RegtxtVatCode.ValidationExpression = VatRegularExpression
    End If
End Sub

Screenshot