简体   繁体   English

如何更改数字输入的格式

[英]How do I change the format of digit inputs

Basically, I want to change a person input from 0######### to (0#)########, the event im using is onblur基本上,我想将一个人的输入从 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;
            }

        }

Your regCheck should be ^\\(0\\d\\)\\d{8}$你的regCheck应该是^\\(0\\d\\)\\d{8}$

Demo演示

Update :更新 :

This regex validates the number of characters, you can omit length check in your code :此正则表达式验证字符数,您可以在代码中省略长度检查:

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;
    }
}

This will check for 10 digits, first number is zero, and that all inputs are digits.这将检查 10 位数字,第一个数字为零,并且所有输入都是数字。 Once all of that passes the code will add the '(' & ')' to it.一旦所有这些都通过,代码将向其添加 '(' & ')' 。 This approach gives specific errors depending on how the user incorrectly entered the number.这种方法会根据用户错误输入数字的方式给出特定错误。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM