I have three fields. The validation should be like so
fieldOne
- Required if fieldTwo not present
fieldTwo
- Required if fieldOne not present
fieldThree
- Always required
So fieldOne
and fieldTwo
depend on each other. Either one or the other can be provided, or they both can be provide. Whatever happens though, fieldThree
is always required.
So far I have the following
var validator = $("#my_form").validate({
groups: {
datagroup: "fieldOne fieldTwo"
},
rules: {
fieldOne: {
require_from_group: [1, '.datagroup'],
email: true,
maxlength: {
param: 40,
depends: function (element) {
var valTwo = $('#fieldTwo').val();
return !valTwo || (valTwo.length < 8) || (valTwo.length > 18);
}
}
},
fieldTwo: {
require_from_group: [1, '.datagroup'],
minlength: {
param: 8,
depends: function (element) {
var valOne = $('#fieldOne').val();
return !valOne || (valOne.length > 40);
}
},
maxlength: {
param: 18,
depends: function (element) {
var valOne = $('#fieldOne').val();
return !valOne || (valOne.length > 40);
}
}
},
fieldThree: {
required: true
}
}
});
Now fieldOne
and fieldTwo
are working well together, but I am having issues making fieldThree
fit in. It kind of works, but if you only provide a value in fieldThree
,although the errors display, the form is still being submitted.
Is there any way to stop this from happening? I am not sure if this needs to be part of the group?
Thanks
UPDATE
<form role="form" id="my_form">
<div class="form-group">
<label for="fieldOne" class="control-label">Field One</label>
<input type="email" id="fieldOne" class="form-control datagroup" name="fieldOne">
</div>
<div class="form-group">
<label for="fieldTwo" class="control-label">Field Two</label>
<input type="tel" id="fieldTwo" class="form-control datagroup" name="fieldTwo">
</div>
<div class="form-group">
<label for="fieldThree" class="control-label">Field Three</label>
<input id="fieldThree" class="form-control datagroup" name="fieldThree" >
</div>
<button class="btn btn-default" type="submit" id="submitButton">Check Information</button>
<div id="error"></div>
<div id="results"><span id="spanOne"></span><br><span id="spanTwo"></span></div>
</form>