How to check if required fields in html form are filled?

I have a submit page in php with an html form that points to the same page. I would like to be able to check if the required fields in the form are not completed so that I can inform the user about it. I would like to know how to do this with php and javascript. However, I believe this is a common problem, so any other answers would be appreciated.

+1


source to share


4 answers


Do validation when submitting part of your php



    if(isset($_POST['save']))
    {
            $fields=array();
            $fields['Nimi']   = $_POST['name'];
            $fields['Kool'] = $_POST['school'];
            $fields['Aadress'] = $_POST['address'];
            $fields['Telefon'] = $_POST['phone'];
            $fields['Email'] = $_POST['email'];

            foreach ($fields as $key => $val)
            {   if(trim($val)=='')
                {   $errmsg=$key." is not filled!";
                    break;
                }
            }
    }

if($errmsg == '')
{ //do your saving here
  exit();
}

if(!isset($_POST['save']) || $errmsg != '')
{ //show your form here
 // and make it to return to the same page on submit
 //<input name="save" type="submit" value="Save" onclick="return true;">
}

      

+2


source


For extra credit, once you know how to do this in PHP and JavaScript from Riho and annakata's answers, then create a way to define a field constraint in a single form that can be rendered as JavaScript for client side validation and run on the server.



Since you need both (client side for user convenience, server side, because we really trust the client very much at this point), it seems like a pretty good idea to support both from the same infrastructure.

+1


source


As far as JS is concerned, you should check before submitting. Typically this involves binding some validation function to the onsubmit trigger of the form, and this validation function will consist of multiple tests for each field of interest.

Most JS libraries have validation implementations that will do most of the work for you, which sounds like it might be a good idea for you. Googling "client side validation" will give endless results, but this (I'm library agnostic, read and choose for myself) should get started *:

http://blog.jquery.com/2007/07/04/about-client-side-form-validation-and-frameworks/

http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype/

http://dojotoolkit.org/book/dojo-book-0-4/part-4-more-widgets/forms/validation

* This is due to how you plan to fish

0


source


The LiveValidation library will help you a lot: http://www.livevalidation.com/

0


source







All Articles