Search code examples
asp.netrequiredfieldvalidator

RequiredFieldValidator Control displays the Error Text on Page_Load


I am having trouble with the <asp:RequiredFieldValidator> in this code.

<asp:Label ID="email_Label" runat="server" Text="Email"></asp:Label>
<asp:TextBox ID="email_Text" runat="server" MaxLength="40" Width="250"></asp:TextBox> *
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="email_Text" Text="Required"></asp:RequiredFieldValidator>

According to the W3schools documentation here I have used the <asp:RequiredFieldValidator> correctly, however instead of displaying the label and text box the page also displays the error message. This happens on page_load so the value has not had a chance to change from the default yet. I want the error text to display after the user clicks the Save button at the bottom of the form I am building.

What is Being Displayed:

Email[TextBox] * Required

What Should Be displayed:

Email[TextBox] *

Am I missing a parent element for the validator or something. According to the example on w3schools site no parent element should be needed. In fact the way they have their example set-up is exactly what I was expecting for this.


Solution

  • Use Validation Group if want to display Error message on Button click. Like this.

    <asp:RequiredFieldValidator ID="rqtxtQName" ValidationGroup="save" ControlToValidate="txtQueueName" runat="server" ErrorMessage="Some required field are missing." SetFocusOnError="True"Display="Dynamic"></asp:RequiredFieldValidator>
    

    and use validation group on Button also.

      <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="save" OnClick="btnSubmit_Click"/>
    

    Hope it will helps.