Alidad;10942392 wrote:I have a PHP Yahoo weather script consisting of a form where you input your zip code.
Yahoo Weather is based on 5 digits ZIP Code
( http://developer.yahoo.com/yui/examples/connection/weather.html )
This makes it very easy to make a <form maxlength="5">
(maxlength="5" makes it impossible to enter longer inputs)
and use [man]preg_match/man to make sure only 5 digits are entered in form
My code below is a script that shows how you can test the input
and maybe send the user back to the form, until ZIP Code is correctly entered.
The preg_match pattern string means this:
full pattern string = '#\d{5}$#'
are only markers for delimiting
so, the test pattern is:
\d{5}$
^ = the beginning of string to be tested
\d{5} = digits 5 (5 digits)
$ = the end of string to be tested
<?php
$error_message = 'Welcome!';
extract($_POST); //Extract $_POST Array into normal variables, like $zip
if(isset($zip)){ //form actually entered?
if( preg_match( '#^\d{5}$#', $zip) ){ //valid 5 digits zip?
$error_message = 'good';
}else{
$error_message = 'not valid zip code';
}
if($error_message == 'good'){
//here we get the weather from Yahooo
echo 'Get Weather!';
exit(); //end script after show weather
}
}
?>
<form method="post" action="">
<input type="text" name="zip" maxlength="5">
ZIP CODE 5 Digits (like: 12345)<br />
<input type="submit" name="zipsubmit" value="GET Weather">
</form>
<?php
echo $error_message;
?>