Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

asp.net validate textbox - at least one text box must have data in

I have three textboxes and I want to validate them. At least one textbox must contain data.

How can I do this?

(The textboxes are Home Phone No., Work Phone No., Mobile No. and I need to check at least one method of contact is specified)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<script language="javascript">
     function Validate(sender, args){    
       args.IsValid = false;    
       if(args.Value != "")    
       {        
         args.IsValid = true;    
    }}</script>

the above function dont validate that at least one textbox contains data it validate that the control attached to the validator have data. Just use one custom validator like this

<asp:TextBox ID="txtHomePhone" runat="server"></asp:TextBox>
<asp:TextBox ID="txtWorkPhone" runat="server"></asp:TextBox>
<asp:TextBox ID="txtMobilePhone" runat="server"></asp:TextBox>

<asp:CustomValidator ID="cvMobilePhone" runat="server" ErrorMessage="ADASDASDA" ClientValidationFunction="Validate"
  ValidateEmptyText="true"></asp:CustomValidator>

<script language="JavaScript">
  function Validate(sender, args) {
    var txt1 = document.getElementById("<%= txtHomePhone.ClientID %>");
    var txt2 = document.getElementById("<%= txtWorkPhone.ClientID%>");
    var txt3 = document.getElementById("<%= txtMobilePhone.ClientID%>");
    args.IsValid = (txt1.value != "") || (txt2.value != "") || (txt3.value != "");
  }
</script>

In case you want to reuse the function you can add attributes to your validation object. Check it out: http://alejandrobog.wordpress.com/2009/09/27/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...