Forum Moderators: open

Message Too Old, No Replies

Regular Expression

Trying to match alpha characters and spaces.

         

Jeremy_H

6:14 pm on Mar 3, 2006 (gmt 0)

10+ Year Member



Hello,

I'm building a form, and one of the input points in their city. I'm trying to use regular expression in the JavaScript to verify before they have submitted their form that they have entered characters that are only allowable for a city name. Alpha characters (Newark) and spaces (San Francisco).

This is what I've written so far, but its not allowing spaces. I was hoping somebody might be able to spot my mistake.

if(/[^a-z]¦^\s/.test(document.q.q103.value)){alert("Error");return false}

Also, I'd be interested to know if there are any other characters that I should allow, like an apostrophes or dash or things like that.

Thanks

Bernard Marx

6:52 pm on Mar 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about

/^[a-z][a-z -]*[a-z]$/i

Begins with alpha, followed by zero or more (alpha, space, hyphen), ending in alpha
- all case insensitive.

Sorry, but this does allow things like "boo--baa", but my brain is starting to hurt.

RonPK

8:54 pm on Mar 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Depending on your audience it may be wiser to explicitly block characters, as that may be easier than to explicitly allow characters. Is there a real need to check the spelling?

Consider city names like

's-Hertogenbosch
München
Krimpen a/d Lek

; your current pattern would block them.

There is a mountain called K2. Surely there must be a city somewhere with a digit in the name?

Jeremy_H

1:45 am on Mar 4, 2006 (gmt 0)

10+ Year Member



Thank you both Bernard and Ron for your help. It's working great now!

Ron, you have an excellent point. There are going to be quite a large array of characters that people could enter in.

I'm creating these checks to make sure that only right and valid information is put into the fields. However, only people in the United States will be given that input field, which I believe will be have far fewer characters used for their city names.

On a similar note. Right after city, is a place for the state abbreviation. In this situation, I know I have only a small list of possible valid entries. I have the regex written down, but for whatever reason it seems that it allows everything BUT a valid entry. I was hoping somebody might be able to take a look and tell me what I'm doing wrong.

Thanks.

if(/^(AA¦AE¦AE¦AE¦AE¦AK¦AL¦AP¦AR¦AS¦AZ¦CA¦CO¦CT¦DC¦DE¦FL¦FM¦GA¦GU¦HI¦IA¦ID¦IL¦IN¦KS¦KY¦LA¦MA¦MD¦ME¦MH¦MI¦MN¦MO¦MP¦MS¦MT¦NC¦ND¦NE¦NH¦NJ¦NM¦NV¦NY¦OH¦OK¦OR¦PA¦PR¦PW¦RI¦SC¦SD¦TN¦TX¦UT¦VA¦VI¦VT¦WA¦WI¦WV¦WY)/.test(document.q.q103.value.toUpperCase())){alert("Please enter a valid state abbreviations.");return false}

RonPK

9:50 am on Mar 4, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if (!/^AA¦AE$/.test(value)) { alert('hey, no match!'); }