Reputation: 2935
How to validate input field to enter mobile number and that mobile number should begins with "07" also if some one enter mobile number with space, space should remove on click. . eg: 07 xxxx xxxx onclick it should be 07xxxxxxxx
Now i used html 5 validation method to give warning:
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="\d{10}">
but this code does not validate it. can someone help me to validate this
Upvotes: 1
Views: 2046
Reputation: 821
When I had to solve the same problem, I used Masked Input Plugin.
Upvotes: 3
Reputation: 513
You asked me to do it using simple javascript.Here is you answer
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
{
var xyz=document.getElementById('mob_no').value.trim();
if(xyz.substr(0,2)==='07')
{
var new_no= document.getElementById('mob_no').value.replace(/\s/g,"")
alert("number after validations check is"+new_no);
}
else
{
alert("incorrect number");
}
}
<input type="text" id="mob_no" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" onblur="myFunction()">
</body>
</html>
Feel free to ask anything and plz repond it worked or not.
Upvotes: 2
Reputation: 1044
I believe, like Niles said you would want to use the pattern pattern="^07\d{8}$"
which means, in english String starting with "07" ending with any numerical sequence equaling 8 characters
Further more, like James was pointing out, use Javascript to remove your whitespaces. However I would add a interval, to clear them automatically so the user understands how the input works for further usage.
<script type="text/javascript">
var inputElm = document.getElementById('phone_number_id_name'), // id="" name of element
input = inputElm.value;
setInterval(function() { inputElm.value = input.replace(/\s+/g, ''); }, 100); // turncate white-space of input every 100ms
</script>
Upvotes: 1
Reputation: 11807
Niles has the right idea.
So, just attach a click handler or a behavior that strips the spaces... ala.
var a = "07989 8989 8 8";
//substitute your element reference ala jQuery('input[name="mobile_number"]');
a = a.replace(/\s+/g,''); // strip the white space
if( /^07\d{8}$/.test(a) ){
// passed test
}else{
// did not pass, show error
}
Upvotes: 1
Reputation: 296
Your pattern for accepting telephone number starting with 07 is
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="^07\d{8}$">
validate 07
at the beginning and after that accept any 8 digit like follow
pattern="^07\d{8}$"
Upvotes: 1