PHP- Validate on certain fields
<p>I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.</p>

<p>My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.</p>

<pre><code>$validate = array(
    array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
    array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
    array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);

$error = '';
foreach ($validate as $validation)
{
    if (!preg_match($validation[1],$validation[0]))
    {
       $error .= $validation[2]; 
    }
}

if($error != '')
{
    echo $error;
    exit;
}
</code></pre>

<p>Comment on this post,if it is not clear.</p>

<p>Thanks in advance!</p>
