3

How to prevent a form from submit if text box is empty?

This I have done in JSP successfully using alert message.

Javascript:

 function validate()
 {
   var x=document.forms["Form1"]["comp"].value;
   if (x==null || x=="")
   {
     alert("comp cannot be blank");
     return false;
   }

   <form name="Form" action="welcome.php" onsubmit="return validate()"  method="post">
      <input type="text" name="comp">

How can I do the same using PHP? So that whenever a user submits without entering text it should give message to user through an javascript alert() message.

I can display alert message:

echo  '<script language="javascript">alert("comp cant blank");</script>';

But how can i give condition?what are the changes has to be made in the above please put it in a code form.i have to do it only in PHP.

6 Answers 6

8

You cannot stop a form from submitting using PHP.

PHP is server side, you would need to have Javascript to handle the form submit if there is an issue with your validation. You should handle validation on both client side (JS) and server side (PHP).

So no, not possible with just PHP as you outlined, the form WILL submit, then you validate it. Can't stop it with PHP (as its just HTML to the user).

Sign up to request clarification or add additional context in comments.

1 Comment

Even if you do validate it using PHP (i'm thinking an ajax submission and server side validation to prevent the form from being submitted) you STILL need to validate again on the actual form submission because a person using firebug, or a browser without javascript can still send bad data.
1

you can used from this jquery code:

$("#btnSubmitID").click(function(event){
     if($("#txtID").val()==''){
          event.PreventDefault();
          alert("your message");
     }
});

this is a sample, you can validate your form with this way before post to the server.

1 Comment

You misunderstood the question, he's not asking for a javascript validation (as he's already doing that)
0

You could submit the form using XHR (known as AJAX) and have php verify the data. You would still need to submit the XHR using javascript.

Comments

0

Your javascript code looks fine and it should not submit the form when its empty. However, if you want to do from PHP code, you can do the same, but the form needs to submit and return back to same page when its not valid (or empty).

Here is sample code

<?php
  if ($_POST['comp'] == '')
   {
    header("location:yourpagename");
  }
else
{
 // process
}
?>

2 Comments

form shouldn't be submit. it jst give message to user the text box shludn't be empty. how can i do this?
when you return false from the javascript code, it should not submit.
0

And now for the non-pseudo code answer. This is working, tested code that elaborates on the concepts I already posted.

<?php
function formWasPosted()
{
    return array_key_exists( 'comp', $_POST );
}
// -------
function validate( &$errors )
{
    if ( $_POST['comp'] == '' )
    {
        $errors['comp'] = 'cannot be blank';
    }

    return count( $errors ) == 0;
}
// -------
function getError( $fieldName, $errors )
{
    $out = '';

    if ( array_key_exists( $fieldName, $errors ) )
    {
        $out = '<span class="errorMsg">' . $errors[$fieldName] . '</span>';
    }

    return $out;
}
//------------------------------------------------------------------------
// $errors will be passed to our validate function so we can set error messages per field if desired.
$errors = array();
$formMsg = '';

if ( formWasPosted() )
{
    if ( validate( $errors ) )
    {
        // do processing here
        header( 'Location: http://www.example.com/success' );
        exit();
    }
    $formMsg = '<div class="errorNotice">There were problems with your submission</div>';
}
?>
<html><head>
<script type="text/javascript">
    function validate()
    {
        var x=document.forms["Form1"]["comp"].value;
        if (x==null || x=="")
        {
            alert("comp cannot be blank");
            return false;
        }
    }
</script>
<style>
.errorMsg, .errorNotice { color: red; }
.errorNotice { font-size: 150%;}
</style>
</head>
<body>
    <?php echo $formMsg; ?>
    <form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
        <label for="comp">Comp <?php echo getError( 'comp', $errors ); ?></label>
        <input id="comp" type="text" name="comp">
    </form>
</body>
</html>

1 Comment

Just so we're clear on this... there is no way to prevent a form from being submitted using php, the best practice is to validate and selectively process based on a form submission.
-1

Here is the general approach I use for processing forms.

Pseudo code:

Has Form Been Submitted?
    Is form valid?
        process form (db insert/update/delete, other operation here
    Else
        Print form with error messages and optionally a javascript alert
    End is form valid
Else
    Print form without error messages
End has form been submitted

3 Comments

Uhm..so OP asks for a php real-time validation and you give him pseudo code validation algorithm? :/ Please guys read the questions well..
If you're using POST, then check $_POST['field_name'] - you can't use DOM addressing in PHP.
@damien I'm inferring his intent from his question - he intends to prevent a form submission from being processed. The question seems confused because of the OP's history with JSP. I'm merely trying to be helpful with my experiences. If someone comes along with a better answer I'm ok with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.