user2100125 user2100125 - 1 month ago 30
Javascript Question

BootstrapValidator conditional validation

I'm using BootstrapValidator and I have some text fields and a radio button with 2 options, I need to validate a text field only if the radiobutton option 2 is selected, how can I obtain it?

This is the form:

<form action="/it/Account/SignUp" class="form-horizontal" id="signup_form" method="post" role="form">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Company</label>
<input type="text" name="company" class="form-control" id="company">
<input type="radio" name="usertype" value="0"><label>Private</label>
<input type="radio" name="usertype" value="1"><label>Company</label>

</form>


This is the JavaScript for BootstrapValidator:

$('#signup_form').bootstrapValidator({
message: 'This value is not valid',
live: 'disabled',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
name: {
validators: {
notEmpty: {
message: 'required'
},
}
},
company: {
validators: {
notEmpty: {
message: 'required'
},
}
},
}
}


I need only to validate the "company" field only if the radio value of 'usertype' is equal to 1

Answer

You should look at the callback validation option

http://bootstrapvalidator.com/validators/callback/

you can create a custom function for validation, return a boolean of true or false, you should then do your checks on the fieldValue depending on if the radio button is checked