简体   繁体   中英

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.

While I know the correct RegExp for this is: /^\\d{13}$/ , I also need it to ignore an empty field. (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.

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

Also, just an alternative to match() , for quicker boolean check use test()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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