views:

1304

answers:

4

I've got a submission page in php with an html form that points back to the same page. I'd like to be able to check if the required fields in the form aren't filled so I can inform the user. I'd like to know how to do that with php and javascript each. However, I imagine this is a common issue so any other answers are welcome.

+1  A: 

Do the check in posting 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;">
}
Riho
A: 

As far as JS goes you have to check before you submit. Generally this involves binding some validation function to the onsubmit event trigger of the form, and that validation function will consist of some tests for each field you're interested.

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 yield infinite results, but this (I'm library agnostic, read and choose for yourself) should get you 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 on the teaching you to fish plan

annakata
+1  A: 

For extra credit, once you know how to do it in PHP and JavaScript from Riho and annakata's answers, then build a way of defining a field constraint in a single form that can both 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're really very much past trusting the client at this point), it seems like quite a decent idea to support both from a single infrastructure.

chaos
A: 

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

nicholaides