How to open the numeric keyboard in mobile and validate the length

How to open the numeric keyboard in mobile and validate the length

Before you submit the data to the server, it required some validation to ensure the inputs are correct. In HTML 5 client-side validation becomes so easy to use and most of us use them in their project frequently. Client-side validation is a kind of check to improve the user experience to let them know what data need to be filed there.

However, client-side validation is not sufficient to ensure data security because we can edit the html5 validation and turn off the javascript validation on the page, and thus we can easily pass the client-side validation, so it is always recommended to have both client and server-side validation on the web app.

In this tutorial we will let you know how you can open the Numeric keyboard in mobile and validate the length. Usually we can achieve this with input type=”number” but in this case we can not use minlength and maxlength in the form. Read below to check how we can achieve this.

//html
<input type="tel" name="" required minlength="10" maxlength="10" class="numbervalidation">
//Javascript
$(document).ready(function(){ 
 $(".numbervalidation").keydown(function(event) {
                k = event.which;
                if ((k >= 48 && k <= 57) || (k >= 96 && k <= 105) || k == 8) {
                    if ($(this).val().length == 10) {
                        if (k == 8) {
                            return true;
                        } else {
                            event.preventDefault();
                            return false;
                        }
                    }
                } else {
                    event.preventDefault();
                    return false;
                }
            });
});