Reputation: 440
I'm using http://jqueryvalidation.org
This works perfectly http://jsfiddle.net/xs5vrrso/
jQuery
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
But it doesn't work when I change the form to be in separate parts like this http://jsfiddle.net/xs5vrrso/578/ (when I click submit it submits the form even though there is a blank required field)
Is that a bug or am I doing something wrong?
Upvotes: 4
Views: 262
Reputation: 388316
The problem is by default the validator will ignore hidden input elements from validation.
When you are go to the part 2, part 1 is hidden so the input fields inside it are also hidden so the validator is ignoring that.
You can use the ignore
option to override this setting, but a better solution will be is to validate the fields before you move to a new part like
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
field1: {
required: true
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
$("#next-btn").click(function () {
if ($('#signup-part-1 :input').valid()) {
$('#signup-part-1').hide();
$('#signup-part-2').show();
}
});
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
field1: {
required: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
$("#next-btn").click(function() {
if ($('#signup-part-1 :input').valid()) {
$('#signup-part-1').hide();
$('#signup-part-2').show();
}
});
#signup-part-2 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="myform">
<div id="signup-part-1">PART 1
<br>
<input type="text" name="field1">
<br>
<button type="button" class="btn-primary pull-right" id="next-btn">Next</button>
</div>
<div id="signup-part-2">PART 2
<br>
<input type="submit">
</div>
</form>
Upvotes: 3