user2431727
user2431727

Reputation: 907

Required Field Validator for textbox having onblur value

I have a textbox having onblur value. When applying it, its corresponding Required Field Validator is not working. My code is here

 <div align="center">
    <asp:TextBox ID="tb_age" runat="server" 
       onfocus="if (this.value == 'Select Age') this.value = '';" 
       onblur="if (this.value == '') this.value = 'Select Age';" 
       value="Select Age" >
    </asp:TextBox>                          
    <asp:RequiredFieldValidator runat="server" id="req_tb_age" 
      controltovalidate="tb_age" errormessage="*" SetFocusOnError="True" 
      Display="Dynamic" />
    <asp:Button ID="bt_show" runat="server"   text="Show"
       CausesValidation="true"  
  onclick="bt_show_data_Click" OnClientClick="Confirm()"/>
</div>

Upvotes: 0

Views: 1004

Answers (5)

Sushmit Patil
Sushmit Patil

Reputation: 1465

As @borissh said you can use placeholder attribute, if you dont want to use placeholder you can add attribute InitialValue="Select Age" to your RequiredFieldValidator control.

You can study more on this here

Upvotes: 2

BorisSh
BorisSh

Reputation: 571

Instead of using your onfocus/onblur events use placeholder="Select Age" attribute for the TextBox.

Upvotes: 2

Bhuban Shrestha
Bhuban Shrestha

Reputation: 1324

Instead of writing inline JS you should write your all JS code in one place. External file is the best way to manage code though you can write file specific JS on same page.

<asp:TextBox ID="tb_age" runat="server" 
       onfocus="Validate(this)" 
       onblur="Validate(this)" 
       value="" >
 </asp:TextBox>

<script type="text/javascript">
   function Validate(elem)
   {
     if (elem.value == '') 
     {
       elem.value = 'Select Age';
     }
   }
</script>

Upvotes: 0

Sudip
Sudip

Reputation: 687

generally, the RequiredFieldValidator gets triggered by the onChange event at the client side. But you are trying to achieve the same by onBlur event. Yoy need to add this snippet to trigger the validator for onBlur Instead-

void Page_Load(object sender, EventArgs e)
{
    txtSummary.Attributes.Add("onblur", "ValidatorValidate(" + reqvalSummary.ClientID + ")");
}

Hope this helps. Or, go to this link to find out more on this.

Upvotes: 0

Hank
Hank

Reputation: 187

The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once.

try this solution

Upvotes: 0

Related Questions