Ângelo Rigo Ângelo Rigo - 5 months ago 12
jQuery Question

Validate text boxes using Jquery Validation

I am using

[Jquery validation plugin][1]


[1]: https://jqueryvalidation.org,


How can i validate if at least one of three options was filled ?

Creating a method via .addMethod ? i am trying to adapt from this fiddle but i have text boxes instead of select boxes:

[validate select box][1]


[1]: http://jsfiddle.net/8x1yj0pr/


I did not get any message, here is what i try until now:

$.validator.addMethod("validateOptions", function(value, element) {
return this.optional( element ) ||
($('#firstname').val() != '' ||
$('#username').val() != '' ||
$('#email').val() != '' ||);
}, "Please provide at least one ");

$(document).ready(function() {
var validator = $("#VerifyForm").validate({
rules: {
formFields: {
validateOptions: true,
}
firstname : {
required: true,
minlength: 2
},
lastname : {
required: true,
minlength: 7
},
email : {
required: true,
minlength: 2
},
},

Answer

No need to use a plugin just for that. Try this:

jsFiddle Demo

$('#submit').click(function(evt){ //<===============================
  var fn = $('#fn').val();
  var un = $('#un').val();
  var em = $('#em').val();
  if (fn !='' || un!='' || em!=''){
    alert('good to go');
  }else{
    evt.preventDefault(); //<===============================
    $('#fn').focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="fn" /><br>
<input type="text" id="un" /><br>
<input type="text" id="em" /><br>
<input type="button" id="submit" value="Submit" />

Comments