zduhac
zduhac

Reputation: 65

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'"/>

Upvotes: 4

Views: 16636

Answers (2)

Todd
Todd

Reputation: 5454

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

Upvotes: 0

rampion
rampion

Reputation: 89053

Very close!

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

You just forgot to specify that the 13 digits started at the start of the string

Upvotes: 8

Related Questions