How to validate input fields?

I need to validate these input fileds,

  1. Only four number can be entered.
  2. Only number can be entered.
  3. Auto tab if fill 4 user inputs.

html,

<div class="row clearfix">
    <ul class="clearfix">
        <li><input type="number" id="num1"></li>
        <li><input type="number" id="num2"></li>
        <li><input type="number" id="num3"></li>
        <li><input type="number" id="num4"></li>
    </ul>
</div>

css,

.row { 
    display:block;
    position:relative;
    width:500px;
}
.clearfix:before,.clearfix:after {  
    visibility: hidden;
     display: block;
     font-size: 0;
     content: " ";
     clear: both;
     height: 0; display:table;
}
ul { 
    list-style:none;
    display:block;
}
.row ul li { float:left; width:75px; margin-right:2px; }

js,

$("#num3").on('keypress', function (event) {
        var key = event.keyCode || event.charCode;
        var maxlength = 4;
        var num1 = $("#num1").val().length;
        var num2 = $("#num2").val().length;
        var num3 = $("#num3").val().length;
        var num4 = $("#num4").val().length;
        $(this).val($(this).val().replace(/[^0-9.]/g,''));
        if($(this).val().length <=  3){
            $('#num3').css('background','#ECECEC');
        }else if(($(this).val().length ==  4)  && (key == 8 || key == 46)){
            $('#num3').css('background','#ECECEC');
        }
        else{
            $('#num4').focus();
            return false;
        }

Here is code: Demo

can you help me?


Source: jquery

Leave a Reply