user499846
user499846

Reputation: 721

Validating form input with regexp

Hi. I have a form that I am using for a google map page and I want to limit the input field to allow only a-z, A-Z, 0-9, spaces and hyphens. I was using:

var postCode = $('#form').val();
Validate = /[a-z0-9 A-Z\-]$/.test(postCode);

if (!Validate) {
    $('#results').html("Please enter alpha numeric (a-z 0-9) characters");
    return;
}

but that doesn't work. Could someone help me fix it?

Upvotes: 0

Views: 230

Answers (2)

Doug Moscrop
Doug Moscrop

Reputation: 4544

^[0-9a-zA-Z]+([ -][0-9a-zA-Z]+)?$

Matches:

90210

abcDEF

abc DEF

abc-DEF

a1b-2c3

But does not match if a leading or trailing space/hyphen is present.

Based on: http://regexpal.com/

Upvotes: 0

KL-7
KL-7

Reputation: 47588

I believe you need /^[a-z0-9 A-Z\-]*$/. Note ^ in the beginning of the string - together with $ at the end it ensures that you validate the whole string and not only its suffix.

If you don't want to accept empty string you can replace * (zero or more quantifier) with + (one or more) or even specify exact range for length like that: /^[a-z0-9 A-Z\-]{3,10}$/.

Upvotes: 2

Related Questions