简体   繁体   中英

Javascript and Required field validator

I have a RequiredFieldValidator on a TextBox. This works fine when nothing is enterd in the TextBox. Now, one more validation I do is when the user enters some junk data, I throw an error-message saying "invalid entry". This is on the Label.

Now the scenario is after the error-message is thrown, if the user empties the textbox and clicks on the button, the RequiredFieldValidator works but the error-message on the label still remains as it is. I would like to hide/remove it once the user empties the textbox.

For this I used a JavaScript function but with this the RequiredFieldValidator does not work. Here's my code:

<asp:TextBox ID="txtemp" runat="server"></asp:TextBox>
<asp:Button ID="btnstatus" runat="server"  ValidationGroup="valgrp1" OnClientClick="Validate()"
    CausesValidation="true"  onclick="btnstatus_Click" 
    Text="Fetch status message" BackColor="#ccebff" />
&nbsp;
<asp:RequiredFieldValidator ID="Reqfield1" ControlToValidate="txtportalid"  ValidationGroup="valgrp1" ErrorMessage="wrong entry" runat="server" />
</div>
<div>
    <asp:Label ID="lblerrormsg" runat="server"  Font-Bold="true"  Visible="false" ForeColor="#FF3300">
    </asp:Label>
</div>

JavaScript:

function Validate()
{
    var txt1 = document.getElementById("<%= Txtemp.ClientID %>");
    var val1 = txt1.value.replace(/\s/g, "");

    if (val1=="")
    {
        document.getElementById("<%= lblerrormsg.ClientID%>").style.display = 'none';
    }
}

I'd suggest using CustomValidator with ClientValidationFunction property set to point to your Validate function like the following:

<script>
    function Validate(source, arguments) {
        arguments.IsValid = /* your validation logic */
    }
</script>

...

<asp:CustomValidator ControlToValidate="txtportalid" 
    ErrorMessage="..." ClientValidationFunction="Validate" runat="server" />

... or, in your case you can just use RegularExpressionValidator . Both will give you the behavior you're looking for.

You could handle the keyup event for the textbox using jQuery .

The example below does two things:

  1. Everytime a keypress occurs on the textbox check whether the textbox is empty and
  2. Check whether the error label has a value

If both the checks have passed, simply clear the error label!

ASPX:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Home</title>
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#txtemp").keyup(function () {
                if (!this.value) {
                    var errorMessage = $("#<%= lblErrorMessage.ClientID %>").length;
                    if (errorMessage) {
                        $("#<%= lblErrorMessage.ClientID %>").html("");
                    }
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtemp" runat="server" />
        <asp:Button ID="btnstatus" runat="server" ValidationGroup="valgrp1" CausesValidation="true"
            OnClick="btnstatus_Click" Text="Fetch status message" />
        <asp:RequiredFieldValidator runat="server" ID="req" ValidationGroup="valgrp1" ControlToValidate="txtemp"
            ErrorMessage="Field is required" />
        <asp:Label ID="lblErrorMessage" ClientIDMode="Static" runat="server" EnableViewState="false" />
    </div>
    </form>
</body>
</html>

Code behind (I've just created a simple method for testing) :

protected void btnstatus_Click(object sender, EventArgs e)
{
    if (txtemp.Text == "invalid")
    {
        lblErrorMessage.Text = "The data is invalid";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM