0

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?

2 Answers 2

2

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}$/.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thats exactly what I needed, I didn't even think about the 0 char entry so that's an added bonus, thanks!
0
^[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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.