简体   繁体   English

正则表达式用于固定位数?

[英]RegEx for fixed number of digits?

I'm finishing a form I have to do for my homework, and just when I thought I was finished, I found a mistake. 我正在完成一份我必须做的作业表格,而当我以为自己完成时,我发现了一个错误。

I need a RegEx for input field that would return an alert if there's not exactly 13 digits. 我需要一个RegEx作为输入字段,如果输入的位数不完全是13位,它将返回警报。

While I know the correct RegExp for this is: /^\\d{13}$/ , I also need it to ignore an empty field. 虽然我知道正确的RegExp是: /^\\d{13}$/ ,但我还需要它来忽略一个空字段。 (Because I don't want the alert to trigger in case the user switches to a different input field) (因为我不希望用户切换到其他输入字段时触发警报)

Just when I thought I had it with: /^$|\\d{13}$/ , it turns out that it will return an alert if there are less than 13 digits but not if there are more, unlike /^\\d{13}$/ that is working fine with 14+ digits. 就在我以为: /^$|\\d{13}$/ ,事实证明,如果少于13位数字,它将返回警报,而如果多于13位,则不会返回警报,这与/^\\d{13}$/可以正常使用14个以上的数字。

Can someone help me out with this? 有人可以帮我这个忙吗? Thanks 谢谢

Here's the rest of the function: 下面是该函数的其余部分:

        function checkNum(box) {
        var re= new RegExp(/^$|\d{13}$/);
        if(!box.value.match(re)) {
            alert("13 numbers are required");
            document.getElementById("numbers").value = '';
        }
    }

And here is the input field: 这是输入字段:

<input type="text" name="numbers" id="numbers" placeholder="Numbers" onFocus="this.placeholder=''" onBlur="checkNum(this); this.placeholder='Numbers'"/>

Very close! 很接近!

/^$|^\d{13}$/

You just forgot to specify that the 13 digits started at the start of the string 您只是忘了指定从字符串开头开始的13位数字

Also, just an alternative to match() , for quicker boolean check use test() 另外,可以作为match()的替代方法,以进行更快的布尔检查,请使用test()

if (!/^\d{13}$/.test(box.value)) {
    alert("13 numbers are required");
    document.getElementById("numbers").value = '';
}

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

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