基本上,我想将人的输入从0 #########更改为(0#)########,使用的事件是onblur
function numberChange(){
var check = document.getElementById("number").value;
var regCheck = /^[0-9]+$/;
if (check != 10 || !regCheck)
{
alert("Please input your 10 digit mobile number")
return false;
}
else if (check == 10 || regCheck)
{
return true;
}
}
答案 0 :(得分:0)
您的regCheck
应为^\(0\d\)\d{8}$
更新:
此正则表达式验证字符数,您可以在代码中省略长度检查:
function numberChange(){
var check = document.getElementById("number").value;
var re = new RegExp(/^\(0\d\)\d{8}$/);
if (re.test(check)) {
return true;
}
else {
alert("Please input your 10 digit mobile number")
return false;
}
}
答案 1 :(得分:0)
这将检查10位数,第一个数字为零,并且所有输入都是数字。一旦完成所有操作,代码将向其添加'('&')'。此方法根据用户错误输入数字的方式提供特定错误。
<html>
<body>
Phone number: <input type="text" id="number" onblur="checkNumber()">
<script>
function checkNumber() {
var x = document.getElementById("number").value;
// Check for 10 digits.
if(x.length != 10) {
alert('The number must be 10 digits.');
return false;
}
// Make sure the first digit is 0.
if(x.charAt(0) != 0) {
alert('The first digit must be 0.');
return false;
}
// Make sure all digits are numbers and not characters.
if(isNaN(x) == true) {
alert('All digits must be numbers.');
return false;
}
// If here then everything else passed so add the '(' and ')' to the number.
document.getElementById("number").value = '(0' + x.charAt(1) + ')' + x.substring(2, 10);
}
</script>
</body>
</html>