I am a beginner in php. And I want to know field level validation using php not by javascript or jquery. How to do this?

My incorrect code:

form  method="POST" action="registrationp.php">
<input type="text" name="emailid"><?php session_start(); if(isset($_SESSION['error'])) {echo $_SESSION['error']; } ?></br>
<input type="submit" name="submit_form" value="Register"></form>


session_start();
if (empty($_POST['emailid'])) {
     $emailid ="Please enter your emailid";
      $_SESSION['error']=$emailid;

}

I tried but it is not working.please guide me.

Hi,

Your script is almost correct but the session_start() must be in the first line of the script. So, if for example you're doing everything in the same script, you can write it like this:

<?php

    session_start();
    $_SESSION['error'] = null;

    if (empty($_POST['emailid']))
    {
        $emailid = "Please enter your email id";
        $_SESSION['error'] = $emailid;
    }

?>

<form  method="POST" action="">
    <input type="text" name="emailid"><?php if(isset($_SESSION['error'])) { echo $_SESSION['error']; } ?></br>
    <input type="submit" name="submit_form" value="Register">
</form>

The session error is null when the script starts, and if $_POST['emailid'] is empty then is set. If it doesn't start null the next time you submit the form it will always show the error message. You could also unset the error session in a second step, it's up to you.

Next control you can add is a filter to validate the email address, so it can become:

<?php

    session_start();
    $_SESSION['error'] = null;
    $_SESSION['emailaddress'] = null;

    if($_POST) print_r($_POST);

    if (empty($_POST['emailid']))
    {
        $emailid = "Please enter your email id";
        $_SESSION['error'] = $emailid;
    }
    else
    {
        $email = filter_var(trim($_POST['emailid']), FILTER_VALIDATE_EMAIL);

        if($email === false)
        {
            $emailid = "Please enter a valid email address";
            $_SESSION['error'] = $emailid;
        }
        else
        {
            $_SESSION['emailaddress'] = $email;
        }
    }

?>

<form  method="POST" action="">
    <input type="text" name="emailid" <?php if(isset($_SESSION['emailaddress'])) echo "value=\"{$_SESSION['emailaddress']}\""; ?>><?php if(isset($_SESSION['error'])) { echo $_SESSION['error']; } ?></br>
    <input type="submit" name="submit_form" value="Register">
</form>

Note that the validation of the email will fail if there are spaces before or after the email string, so it's important to use the trim() function to remove them.

Documentation:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.