How to allow only phone number in input and make it validate

Manideepgoud
Posted by Manideepgoud under jQuery category on | Points: 40 | Views : 1508
Hi,
In the below code, am showing how to allow only numbers without text and get alert if we give more than 10 numbers?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
function validatephone(phone)
{
var maintainplus = '';
var numval = phone.value;
if(phone.value.length > 10){
alert("Please enter the valid Phone number")
}

if ( numval.charAt(0)=='+' )
{
var maintainplus = '';
}
curphonevar = numval.replace(/[\\A-Za-z!"£$%^&\,()*+_={};:'@#~,.Š\/<>?|`¬\]\[]/g,'');
phone.value = maintainplus + curphonevar;
var maintainplus = '';
phone.focus;
}
</script>
</head>
<body>

<div class="container">
<label>Phone Number:</label>
<input type="text" name="country_code" onkeyup="validatephone(this);" id="phone"/>
</div>

</body>
</html>

Hope This code might help you.
Thanks,
Manideep

Comments or Responses

Login to post response