validate forms in function of select

1

I'm working with html5 and need to validate one field on my form depending on another.

I have a% field of% named Document Type , with three possible options (BI, Dire, passport) and a different Document Number field. I need that when an option that is selected in <select> (eg passport), filling in the Document Number field will only accept passport characters and becomes mandatory.

    
asked by anonymous 21.03.2018 / 11:22

1 answer

0
  

There are many ways to do it, I used jQuery and jQueryMask which is   a plugin that formats the inputs according to the rule that   we define, could also be done with regular expression.

$('#divCampo').hide();

  $(document).ready(function(){
	$('#sel').on('change', function(){
	  var sel = $('[name="sel"]').val();
	  var select = $('#sel :selected').text();
	  var esvaziaCampo = $('#campo').val('');
				
		if (sel == '0') {
			$('#divCampo').hide();
		}
		else if (sel == '1') {
			$('#divCampo').show();
			$('#campo').mask('000-000');
			$('#texto').text(select);
		}
		else if (sel == '2') {
			$('#divCampo').show();
			$('#campo').mask('000-000-000');
					$('#texto').text(select);
		}
		else if (sel == '3') {
			$('#divCampo').show();
			$('#campo').mask('(000) 0000-00000');
			$('#texto').text(select);
		}
				
	});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script><formaction="https://www.google.com">
	<div class="col-md-6 col-md-offset-3" style="margin-top:25px;">
		<label for="sel">Tipo de documento</label>
		<select class="form-control" name="sel" id="sel">
			<option value="0"></option>
			<option value="1">BI</option>
			<option value="2">Dire</option>
			<option value="3">Passaporte</option>
		</select>
	</div>

	<div class="col-md-6 col-md-offset-3" id="divCampo" style="margin-top:25px;">
             <label for="campo">Preencha o campo <span id="texto"></span></label>
	     <input class="form-control" type="text" id="campo" required><br>
	     <input type="submit" class="btn btn-primary" id="btn" value="Enviar">
	</div>
</form>
    
23.03.2018 / 20:00