tags:

views:

42

answers:

2

There are two textboxes one for email and other one for phone i have used one custom validation control so that user have to fill any one of textboxes for client side i used javascript

function ValidatePhoneEmail(source, args) {

        var tboxEmail = document.getElementById('<%= tboxEmail.ClientID %>');
        var tboxPhone = document.getElementById('<%= tboxPhone.ClientID %>');
        if (tboxEmail.value.trim() != '' || tboxPhone.value.trim() != '') {
            args.IsValid = true;
        }
        else {
            args.IsValid = false;
        }
    }

how to achieve same result using jquery

+2  A: 

The exact validation plugin equivalent would be to use "required" on those fields, like this:

$(function() {
  $("form").validate({
    rules: {
      <%= tboxEmail.UniqueID %>: "required",
      <%= tboxPhone.UniqueID %>: "required"
    }
  });
});

You can see a full list of options here. If you wanted to add a custom message and validate that it is a valid email address, you can do it like this:

$(function() {
  $("form").validate({
    rules: {
      <%= tboxEmail.UniqueID %>: { required: true, email: true },
      <%= tboxPhone.UniqueID %>: "required"
    },
    messages: {
      <%= tboxEmail.UniqueID %>: "Please enter a valid email address",
      <%= tboxPhone.UniqueID %>: "Please enter a phone number"
    }
  });
});
Nick Craver
if you have $("form") it will not work in web form and it has to be "aspnetForm"
Abu Hamzah
@Abu - `$("form")` looks for `<form>`, there's only one of these with asp.net webforms so this works. You're thinking of the ID selector, which would be `$("#aspnetForm")` which looks for `<elem id="aspnetForm">`, kind of a different approach entirely...also, `aspnetForm` is just the default name, so that's not a safe recommendation, whereas `$("form")` should work for 99% of asp.net webforms scenarios.
Nick Craver
@Nick: thanks i didnt know about that.
Abu Hamzah
A: 
  <script type="text/javascript"> 
        $(document).ready(function() { 
            $("#aspnetForm").validate({ 
                rules: { 
                    <%=txtName.UniqueID %>: { 
                        minlength: 2, 
                        required: true 
                    }, 
                     <%=txtEmail.UniqueID %>: {                         
                        required: true, 
                        email:true 
                    } 
                }, messages: { 
                    <%=txtName.UniqueID %>:{  
                        required: "* Required Field *",  
                        minlength: "* Please enter atleast 2 characters *"  
                    } 
                } 
            }); 
        }); 
    </script> 

    Name: <asp:TextBox ID="txtName"   runat="server" /><br /> 
    Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br /> 
Abu Hamzah