[英]Javascript/JQuery how to validate phone number
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. 如何验证输入字段以输入手机号码,该手机号码也应以“ 07”开头,如果有人用空格输入手机号码,则单击时应删除空格。 .
。 eg: 07 xxxx xxxx onclick it should be 07xxxxxxxx
例如:07 xxxx xxxx onclick,应为07xxxxxxxx
Now i used html 5 validation method to give warning: 现在,我使用html 5验证方法发出警告:
<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
有人可以帮我验证一下吗
当我必须解决相同的问题时,我使用了Masked Input Plugin。
You asked me to do it using simple javascript.Here is you answer 您要求我使用简单的javascript进行操作。
<!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. 随时提出任何问题,请回复是否有效。
Your pattern for accepting telephone number starting with 07 is 您以07开头的电话号码的接受方式是
<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 首先验证
07
,然后再接受以下8位数字,如下所示
pattern="^07\d{8}$"
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
}
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
我相信,就像Niles所说的那样,您将希望使用模式
pattern="^07\\d{8}$"
,这意味着,在英语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. 此外,就像James指出的那样,请使用Javascript删除空格。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.