So, the Regular Expression Validator cannot be made invisible or enable is equal to false. The images below describes everything.
<asp:Label runat="server"
CssClass="col-md-2 col-form-label" ForeColor="White" Font-Size="Medium">NIC or Passport number:</asp:Label>
<div class="col-md-3">
<asp:UpdatePanel runat="server" ID="updatePanel2" UpdateMode="Conditional" RenderMode="Block">
<ContentTemplate>
<asp:TextBox runat="server" ViewStateMode="Enabled" AutoComplete="off" ID="txtnic" AutoPostBack="true" OnTextChanged="txtnic_TextChanged" CssClass="form-control" />
<asp:Label runat="server" Visible="false" ID="lblnic" BackColor="White" ForeColor="Red"></asp:Label>
<asp:Panel runat="server" Visible="false" ID="pnltick2">
<lord-icon
src="https://cdn.lordicon.com/oqdmuxru.json"
trigger="in"
delay="0"
state="in-check"
style="width: 30px; height: 30px; color: lawngreen; background-color: greenyellow">
</lord-icon>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtnic" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Display="Dynamic" ControlToValidate="txtnic" ErrorMessage="Invalid NIC or Passport number format. Please check and try again." ForeColor="Red" SetFocusOnError="true" ValidationExpression="^[A-Za-z][0-9]{13}$|^[0-9]{8,12}$">
</asp:RegularExpressionValidator>
The code behind on Text changed.
// Creating Connection.
SqlConnection con5 = new SqlConnection(_conString);
// Creating Command.
SqlCommand cmd5 = new SqlCommand();
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
creating a parameterized query for the Username
cmd5.Parameters.AddWithValue("@national", passwordEncryption(txtnic.Text.Trim()));
search for username from tbl_organizer and tbl donor
cmd5.CommandText = "select don_nic_pass from tbl_donor where don_nic_pass=@national";
Creating DataReader to read from database.
SqlDataReader dr;
con5.Open();
dr = cmd5.ExecuteReader();
string input = txtnic.Text;
if (Regex.IsMatch(input, "^[A-Za-z][0-9]{13}$|^[0-9]{8,12}$"))
{
RegularExpressionValidator1.Visible = false;
RegularExpressionValidator1.Text = "";
lblnic.Text = "";
Checking if username already exists in the DB.
if (dr.HasRows)
{
pnltick2.Visible = false;
lblnic.Visible = true;
txtnic.Focus();
lblnic.Text = "Nic Already Exists!";
RegularExpressionValidator1.Visible = false;
}
else
{
lblnic.Visible = false;
pnltick2.Visible = true;
lblnic.Text = "";
RegularExpressionValidator1.Visible = false;
}
}
else
{
RegularExpressionValidator1.Enabled = true;
RegularExpressionValidator1.Text = "(Invalid Nic/Passport number!)";
}
}
[This should not happen because it is not match with if (Regex.IsMatch(input, "^A-Za-z][0-9] {13}$|^[0-9]{8,12}$"))