0

I need to validate form using Jquery, below is my sample code

<input type="checkbox" name="field_1" />
<input type="checkbox" name="field_2" />

In the above two field any one field is required,I know this would be achieve by using radio button,for some reason I am using checkbox,I am trying below validation code,but I validate both fields

 $('#myForm').validate({
    rules: {
        field_1: {
            required: true,
            number: true
        },
        field_2: {
            required: true,
            number: true
        }
    }
});

Any help is appreciated...

10
  • 2
    Possible duplicate of jQuery Validation plugin: validate check box Commented Apr 18, 2017 at 5:33
  • refer the example stackoverflow.com/questions/15453036/… Commented Apr 18, 2017 at 5:34
  • write custom validation, your code won't work, which is pure field validation Commented Apr 18, 2017 at 5:35
  • stackoverflow.com/questions/3035634/… plz refer this Commented Apr 18, 2017 at 5:36
  • Do you need your fields name should be different as above like field_1 & field_2 or can able to change this to the same name as field? Commented Apr 18, 2017 at 5:39

1 Answer 1

0

Check below output,

$('#myForm').validate({
  rules: {},
  messages: {},
  errorPlacement: function(error, element) {
    error.appendTo(element.parent("td").next("td"));
  },
  submitHandler: function(form) {
  	if($(".chk:checkbox:checked").length == 1)
  	form.submit();
    else
    alert("Please select only once checkbox value..!");
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form name="asada" id="myForm" action="">
  <input type="checkbox" name="field_1" class='chk' />
  <input type="checkbox" name="field_2" class='chk' />
  <input type="submit" />
</form>

I am operating in submit handler, there I am checking for strict check only one checkbox should be selected, else form wont submit.

I hope this will help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.