I have four input elements (i.e. textboxes) in my form for user to enter different phone nos i.e. office, handphone, home, etc. (These input fields are not necessarily under one div/group) Before submit, I want to validate these phone no. entries and make sure that atleast one of the phone no is entered by user. If none of the phone no. field has valid entry my form should not get validated and should not post.
I use ParsleyJS library for validation and use knockout.js.
I have following code for one field in my Razor view (rest three fields are similar to this):
<div class="col-md-3 clmargin">
<div class="form-group col-md-4 zeropadding div2adjustments">
@Html.LabelFor(m => m.Handphone, new { @class = "fieldtext" })
</div>
<div class="col-md-8 ">
<input type="text" class="form-control fieldtextinput input-sm" maxlength="10" minlength="8" data-parsley-type="digits"
data-bind="value:Handphone, disable:ViewMode() == 'View'" id="handphone">
</div>
</div>
I have given id to my input i.e. "handphone" in above code.
Javascript code :
$(document).ready(function () {
$('#contact').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (document.getElementById("other").value == '' && document.getElementById("telephone").value == '' &&
document.getElementById("office").value == '' && document.getElementById("handphone").value == ''){
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("Provide atleast one contact no")
.addClass("filled");
return;
}
$('.invalid-form-error-message').html('');
return;
});
});
With above script code it can detect the invalid scenario but doesn't prevent the form submit.
I have taken above script code from here