Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2008
    Location
    pakistan
    Posts
    109

    Unanswered: Validation using php

    i want to do form validation using php when field left empty and submit a form
    if field is empty then show fill in the name on this page like this
    Attached Thumbnails Attached Thumbnails firm.JPG  

  2. #2
    Join Date
    Jun 2010
    Location
    New Zealand
    Posts
    15
    The most basic approach you can use is manually validating each field and returning an error message if validation fails:

    PHP Code:
    <?php
    if (isset($_POST['submit']))
    {
        
    $success TRUE;

        
    //Put each $_POST value into its own array
        
    foreach ($_POST as $key => $val)
        {
            $
    $key $val;
        }

        
    //Form validation starts here
        
    if (empty($message))
        {
            
    $success FALSE;
            
    $message_error 'The message field cannot be empty.';
        }

        if (
    $success == TRUEredirect('/success_page.php');
    }
    ?>

    <form action="this_page.php">
    <label for="message">Name:</label> <input type="text" name="message" id="message" value="<?=$message?>" />
    <?php if (!empty($message_error)) echo $message_error?>

    <br />
    <input type="submit" name="submit" value="Send Message" />
    </form>
    There are loads of nice validation libraries available that will take care of the hard work for you. CodeIgniter is an MVC framework that has a great validation library - definitely worth checking out.

  3. #3
    Join Date
    Jun 2010
    Posts
    6
    If you don't want to do verification of all form fields, you just can register an array and its keys have to be composite from require fields name like keys ...
    PHP Code:
    <?php

    $reauireFields 
    = array('fieldOne''fieldTwo');
    if (isset(
    $_POST['submit']))
    {
        
    $success TRUE;

        foreach (
    $reauireFields as $key => $val)
        {
            if(empty(
    $_POST[$key])) {
                
    $success FALSE;
                
    $message_error[$key] = 'The message field cannot be empty.';
            }
        }

        if (
    $success == TRUEredirect('/success_page.php');
    }
    ?>

    <form action="this_page.php">
        <label for="fieldOne">fieldOneName:</label> 
        <input type="text" name="fieldOne" id="fieldOne" value="<?=$_POST['fieldOne']?>" />
    <?php if (!empty($message_error['fieldOne'])) echo $message_error['fieldOne']; ?>

    <br />
    <input type="submit" name="submit" value="Send Message" />
    </form>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •