0

I have a form in which a user enters a 13 digits numeric value and i try to use minlength attribute but its not working. So i try javascript and it works fine but when the focus losses from Input then the function onblur calling again and again. the code is under HTML

<input type='number' id='cnc' pattern='[0-9]{13,13}' name='cnic' oninput="javascript: if (this.value.length > 13) this.value = this.value.slice(0, 13);" minlength="13" onblur="checkLength(this);" placeholder="Enter CNIC without dashes: e.g 6110122334455" class='form-control' required value="<?php echo isset($_POST['cnic']) ? htmlspecialchars($_POST['cnic'], ENT_QUOTES) : "";  ?>" />

Javascript

function checkLength(el) {
  if (el.value.length != 13) {
    alert("CNIC length should be 13 digits");

    document.getElementById("cnc").focus();

document.getElementById("cnc").select();  

  }

Now i want that the control/cursor to the input field if user not entered 13 digit code and moves to other input field

SKYz
  • 67
  • 6

2 Answers2

1

Try this regex method to verify the Pakistani CNIC format:

jQuery('#cnic').blur(function(){
  var input_text = jQuery(this).val(),
  myRegExp = new RegExp(/\d{5}-\d{7}-\d/);

  if(myRegExp.test(input_text)) {
      //if true
      jQuery('#cninc_msg').text('Correct');
 
  }
  else {
      //if false
      jQuery('#cninc_msg').text('Enter CNIC in correct format. 12345-1234567-1');
  }
  });
  
 jQuery('#cnic2').blur(function(){
  var input_text = jQuery(this).val();
  if(input_text.length != 13 ){
    jQuery('#cninc2_msg').text('Error');
  }
  else{
jQuery('#cninc2_msg').text('OK');
  }
  });
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="cnic" name="cnic" placeholder="42212-1234567-1" />
<span id="cninc_msg"> </span>

Without Dashes simply check this

<input type="text" id="cnic2" name="cnic" placeholder="4221212345671" />
<span id="cninc2_msg"> </span>

This is just a basic example. You can use this on on key up or onkeyDown events as per your requirements.

Optimum Creative
  • 1,438
  • 13
  • 21
0

minlength is not yet supported by any browser. Try this instead

JLai
  • 340
  • 1
  • 8