PDA

View Full Version : check input for specific string


bk1
12-30-2002, 10:33 PM
Hi,

I have a text input for "Street Address" in a form and want to prevent the form from being submitted if the input contains "PO Box" or any combination like "po box", "P.O. box" etc...

I think I understand the steps to do it, but I can't figure out how to write the script.

If the street address is not blank, I want to:

1. convert all characters to lower case
2. strip out occurances of "."
3. check for "po" or "box"
4. return false if found on submission

Can anyone help out with some code or suggest a better way of accomplishing this? Thanks in advance!

chrismiceli
12-30-2002, 10:39 PM
try this.

<script>
function valid() {
test = document.myform.street.value;
if (test == "") {
return false
}
test = test.toLowerCase();
string = string.replace(".", "");
if (string.indexOf("po") != -1 || string.indexOf("box") != -1) {
return false
}
else
return true
}
</script>
<form name="myform" onSubmit="return valid()">
<input type="text" name="street" value="">
<input type="submit">
</form>

bk1
12-30-2002, 11:24 PM
Awesome! Thanks a lot, chrismiceli!

chrismiceli
12-30-2002, 11:46 PM
no prob ;)

bk1
12-30-2002, 11:53 PM
one last queston... (hopefully!)

If I enter "Potomac Way" or "Boxster Place", it returns false. Any ideas how to check for isolated occurances of "po" and "box" that aren't contained in other words or strings?

chrismiceli
12-31-2002, 04:32 AM
try this.

<script>
function valid() {
test = document.myform.street.value;
if (test == "") {
return false
}
test = test.toLowerCase();
string = string.replace(".", "");
if (string.indexOf("p") != -1 && string.indexOf("box") != -1) {
return false
}
else
return true
}
</script>
<form name="myform" onSubmit="return valid()">
<input type="text" name="street" value="">
<input type="submit">
</form>

whammy
12-31-2002, 11:13 PM
A regular expression would be better for this (not to mention much less code!), i.e.:

<script type="text/javascript">
<!--
function containsPoBox(str) {
return !/P[. ]?O[. ]?BOX/gi.test(str);
}
// -->
</script>

<form id="form1" method="get" action="testaddress.htm" onsubmit="return containsPoBox(this.address.value)">
Address: <input type="text" name="address" /><br />
<input type="submit" value="Submit" />
</form>


A regular expression can be written to do just about any kind of validation you want, I just went by what you specified in your first post. ;)

P.S. Although the letters are capitalized in the regular expression, the /gi switches (or modifiers?) specifies to test the string "globally" (g) and "ignore case" (i), meaning it will catch upper AND lower case versions...

chrismiceli
01-01-2003, 06:37 AM
you know i am still learning reg exp whammy!

bk1
01-02-2003, 04:21 PM
thanks whammy. I'm reading up on regular expressions now...