SagarPPanchal
SagarPPanchal

Reputation: 10131

Server Side Validation using PHP script

I have written this code for Form using Server Side Validation in CORE PHP

                if(empty($s_email)){
                $er = "Please enter E-mail";
                }else if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $s_email)){
                $er="Email-ID is invalid!<br>";
                }else if(!filter_var($s_secemail, FILTER_VALIDATE_EMAIL)){
                $er="Secondary Email-ID is invalid!<br>";


               <p>
                  <label class="required" for="s_email">Email Address:</label><br/>
                                <input type="text" id="s_email" class="half" value="" name="s_email"/>
                            </p>

                            <p>
                                <label for="s_secemail">Secondary Email Address:</label><br/>
                                <input type="text" id="s_secemail" class="half" value="" name="s_secemail"/>
                            </p>

My problem is when I skip the $s_secemail field, I am getting this meassage "Secondary Email-ID is invalid", its not mandatory

Upvotes: 0

Views: 6175

Answers (3)

gaurav vashisht
gaurav vashisht

Reputation: 49

i found good source for implementing server side validation so would like to share http://www.webexpertlabs.com/server-side-form-validation-using-regular-expression/

Upvotes: 0

sAnS
sAnS

Reputation: 1163

You may try like this only check $s_secemail is valid email or not if is not empty as the below code

if(empty($s_email)){
                    $er = "Please enter E-mail";
                    }else if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $s_email)){
                    $er="Email-ID is invalid!<br>";
                    }else if(!empty($s_secemail) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $s_secemail)){

                $er="Secondary Email-ID is invalid!<br>";

                    }


                   <p>
                      <label class="required" for="s_email">Email Address:</label><br/>
                                    <input type="text" id="s_email" class="half" value="" name="s_email"/>
                                </p>

                                <p>
                                    <label for="s_secemail">Secondary Email Address:</label><br/>
                                    <input type="text" id="s_secemail" class="half" value="" name="s_secemail"/>
                                </p>

Upvotes: 1

Sagish
Sagish

Reputation: 1065

use else if (!empty($s_secemail) && !filter_var($s_secemail, FILTER_VALIDATE_EMAIL)) to only check the condition if $s_secemail is provided

Upvotes: 2

Related Questions