Originally posted by indrajit_m
Dear all,
In my work, I have to validate some fields whether they contains characters or numbers. For this I wrote the following code. But the problem I am facing is: it is validating the last field only. I think it is a mistake in the loop constructed by me. Can anybody debug it and correct me in this way?
if((!$country) || (!(preg_match('/^[a-zA-Z]*$/',$country))))
{
$stop = "<center><font class=\"pn-title\">"._COUNTRYNULL."</center></font>";
}
if((!$zip) || (!(preg_match('/^[0-91]*$/',$zip))))
{
$stop = "<center><font class=\"pn-title\">"._ZIPNULL."</center></font>";
}
if((!$phnumber) || (!(preg_match('/^[0-9]*$/',$phnumber))))
{
$stop = "<center><font class=\"pn-title\">"._PHONENULL."</center></font>";
}
if((!$fax) || (!(preg_match('/^[0-9]*$/',$fax))))
{
$stop = "<center><font class=\"pn-title\">"._FAXNULL."</center></font>";
}
Thanking you,
Regards,
Indrajit. [/B]
One problem with your loop is that you don't have one 🙂.
Another problem is that you're not using or saving any of your error messages before you destroy them with new ones. If $country and $fax are both failures, $stop first gets set to an error message saying the country is bad, but then that gets discarded, and replaced with another error message that says the fax number is bad.
$stop='';
if(!$country || !preg_match(...))
{
$stop .= "<center>....</center>";
}
...
if(!$fax || !preg_match(...))
{
$stop .= "<center>....</center>";
}
This may relieve your immediate problem. But...
"East Timor", "New Zealand" and "United States" are valid names for countries, but they'll fail your test because of the spaces they contain.
Fax and phone numbers are often written with extra decorations like spaces, brackets and hyphens. These would need to be stripped out before checking that what remains consists entirely of digits.
Some territories (such as the United Kingdom) have postal codes that use letters as well as digits.
In short, you might want to rethink just what you want to check for when you're validating these.
Oh, and your HTML tags are not properly nested 🙂. Consider using <span> instead of <font>, or drop the <center><span> pair and use a single <div class='pn-title'> entity with the text-centring built into the style.