How to allow only 10 digit number validation in Jquery?

jquery

Nicesnippets

19364

07-01-2020


Hi Guys,

In this tutorial,i will tell how you can allow only 10 numbers in textbox using jquery .we just allow only 10 digit number validation in jquery. user can only enter 10 numbers in textbox using jquery for phone number or mobile validation.

I will give you simple four example of how to restrict user to type 10 digit numbers in input element.we can do it that thing multiple way.i will show different example of only 10 digit validation in html

One it using pattern attribute in html and another is maxlength and jquery keypress event. So you can just see both example. You can see also preview bellow. You can use anyone as you want.

here blow the example allow only 10 numbers in textbox using jquery.

Example 1


<!DOCTYPE html>

<html>

<head>

<title>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</title>

</head>

<body>

<form>

<h1>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</h1>

<label>Numbers</label>

<input type="text" name="num" placeholder="Enter numbers" pattern="\d{10}" maxlength="10">

<button type="submit">Submit</button>

</form>

</body>

</html>

Example 2

<!DOCTYPE html>

<html>

<head>

<title>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</title>

</head>

<body>

<form>

<h1>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</h1>

<label>Numbers</label>

<input type="text" name="num" placeholder="Enter numbers" pattern="[1-9]{1}[0-9]{9}" maxlength="10">

<button type="submit">Submit</button>

</form>

</body>

</html>

Example 3

<!DOCTYPE html>

<html>

<head>

<title>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>

<body>

<form>

<h1>How to allow only 10 digit number validation in Jquery? - nicesnippets.com</h1>

<label>Moblie No</label>

<input type="text" name="moblie_no" class="moblie-no" placeholder="Enter numbers">

<button type="submit">Submit</button>

</form>

</body>

<script type="text/javascript">

$("input[name=moblie_no]").attr("maxlength", "10");

$('.moblie-no').keypress(function(e) {

var arr = [];

var kk = e.which;

for (i = 48; i < 58; i++)

arr.push();

if (!(arr.indexOf(kk)>=0))

e.preventDefault();

});

</script>

</html>

It will help you....


Recommended Posts