Jump to content

Validate a text field for multiple criteria


jay.barnes

Recommended Posts

Hi, all!

 

I've got a field that I need users to fill with either:

 

1. An American postal code (example: "47582")

2. A Canadian postal code (example: "A8G 1F4")

3. A city/state abbreviation (example: "Atlanta, GA", or "Quebec City, QC")

 

I know how to make sure that they only enter numbers in the field, but that would not allow option 2 or 3.  The best validation checks I can make are:

 

if the entry is all letters (and possibly spaces or commas)

- assume the entry is a city/state combination

- make sure that there are two letters after the comma or final space in the string

 

if the entry is all numbers

- assume the the entry is an American postal code

- make sure that there are only five digits in the entry

 

if the entry is a combination letters and numbers

- Assume the entry is a Canadian postal code

- make sure that the entry follows the "A1A 1A1" format

 

so, that's my question: How do I make the form element "document.form.text_field.value" look for such values?

 

Thank you!

 

Link to comment
Share on other sites

Still researching this issue....

 

I think I've found the criteria that I'm looking for, would like some help with my syntax, though....

 

function hasNumbers(string) {
    var regex = /\d/g;
    return regex.test(string);
} 

function validateOriginFormat() {
    var error = "";

    if (
	(document.load_search.Search_Origin_Type_1.checked == true)&&
	(!hasNumbers(document.load_search.Search_Origin_Radius_Point.value))&&//if the value of the field has no numbers in it, and, thusly is not an american or canadian zip code
	(document.load_search.Search_Origin_Radius_Point.value.substr(-3, 1)//and the third to last character of the value is not a letter or number
	)
{
        error = "Please use a valid city/state format (example: Boston, MA or Toronto, ON) in Step 3!\n"//recognize the the intended input was a city and state, but the proper format of "City, ST" was not used.
        }
    return error;  
}

 

Anyone able to point me in the right direction in regards to where I'm going wrong with my syntax?  Thanks!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.