todd.pund
todd.pund

Reputation: 689

Javascript + Regex = Breaks function call somehow

html code:

<div class="submitForm">
  <input type="button" value="button" onclick="doValidateForm();" /></div>

javascript:

<script type="text/javascript">
  function doValidateForm() {
    if (!/^[0-9]+${5}/.test(zip) && zip != "") {
      alert("Zip has invalid characters.");
      return false;
    }
  }
</script>

The problem is the {5}. With it in I get "JavaScript runtime error: 'doValidateForm' is undefined." I've moved the {5} around in the expression. With it not there, the code executes fine.

I've tried:

/^[0-9]{5}+$/.test(zip)

and

/^{5}[0-9]+$/.test(zip)

But it still breaks. Any help would be greatly appreciated.

edit fixed code.

Upvotes: 0

Views: 84

Answers (2)

frnhr
frnhr

Reputation: 12903

You are probably looking for this regex:

/^[0-9]{5}$/

It matches 5-digit numbers (with leading zeroes counting as digits)

Use it like this:

if (!/^[0-9]{5}$/.test(zip)) { ...

Quick explanation:

+ means "once or more"
{5} means "exactly 5 times"

So is doesn't make sense to have + and {5} one after the other in any regex. It's kinda like asking javascript to calculate what 3+*5 is. It's just a rough comparison - the similarity lies in operators being used without operands)

Upvotes: 1

anubhava
anubhava

Reputation: 785846

This condition:

if (!/^[0-9]+${5}/.test(zip) && zip != "")

should be rewritten as:

if (/^\d{5}$/.test(zip) == false) {

Upvotes: 1

Related Questions