0
votes

I have 3 fields I want to validate validate all 3 fields and allow the form to be submitted if a minimum of one field is filled. I am unable to do that.

Please check my code:

<script type="text/javascript">
    $(function(){  
        $("#field1").validate({
            expression: "if (VAL) return true; else return false;",
             message: "Please enter username!",
        });                
         $("#field2").validate({
            expression: "if (VAL) return true; else return false;",
             message: "Please enter username!",
        });
        $("#field3").validate({
            expression: "if (VAL) return true; else return false;",
             message: "Please enter username!",
        });

    });          
 </script>

HTML-

<form>
  <input type="text" id="field1" />  <!-- username1 -->
  <input type="text" id="field2" />  <!-- username2 -->
  <input type="text" id="field3" />  <!-- username3 -->
  <input type="submit id="submit" value="Submit" />
</form>

In the above code, the validation requires all fields to be filled. But my requirement is only one field needs to be filled. If I leave all fields, then the message "Please enter username!" will show.

JSFIDDLE

1
Is .validate() a plugin or your own method? Perhaps you can set this up as a jsFiddle? - Moob
No i am using jquery.validate.js and jquery.validation.functions.js - Developer
There's not enough info here for us to answer. Maybe one of those plugins already has the ability to do as you require. Could you give those fields the same name or class? $("input[name='username']").validate({.... WHY do you have 3 fields for the same thing anyway!? - Moob
this can also be done by just a jquery code, there's no need to add a plugin for this.. to achieve it you can write the code as $("input[type=text]").each(function(){ if($(this).val().length > 0) alert('user has inputted'); }). For checking you can store the lengths in a array and check if any value is greater than 0 then proceed for submit else show message :) - D.T.

1 Answers

0
votes

As per your requirements , check it out :

<form action="" onsubmit="return validateForm();" >
    <input type="text" id="field1" name="field1" />  <!-- username1 -->
    <input type="text" id="field2" name="field2" />  <!-- username2 -->
    <input type="text" id="field3" name="field3" />  <!-- username3 -->
    <input type="submit" id="submit" name="submit" value="Submit" />
</form>

<script>
    function validateForm()
    {
        field1=$('#field1').val();
        field2=$('#field2').val();
        field3=$('#field3').val();

        if(field1 == '' && field2 == '' && field3 == '')
        {
            alert('Please fill atleast one field.');
            return false;
        }
        else
        {
            return true;
        }
    }
</script>