Jump to content

Easy NOOB problem! Form Validation


mwktar

Recommended Posts

HI guys, I have a form that works the sum of 2 numbers after submission - I'm using 

if (isset($_POST['num1']) && ($_POST['num2']))

to check the user has entered the numbers - if not it displays a validation message saying please enter 2 numbers. If the user enters the first number and not the second it outputs the message, but if they enter only the second it accepts the first empty box as a zero

Link to comment
Share on other sites

isset() tests whether the form field was submitted at all, as in whether the field was part of the form or not. It doesn't check if the value is an empty string.

 

Are you using isset() to see if the form was submitted? I suggest checking for the submit button instead

 
if (isset($_POST["submit"])) {
And I suggest keeping that separate from the validation check.

 

Supposedly one should also use isset() on the individual form fields, but in practice nobody cares about that. So once you know the form was submitted, all you have to do is check the two values aren't empty strings.

if ($_POST["num1"] != "" && $_POST["num2"] != "") {
Note that you cannot simply do

if ($_POST["num1"] && $_POST["num2"]) {
because the string "0", which would be a perfectly valid thing to use in your particular form, is also considered false-y.

 

When that's working, you should consider adding more validation to make sure the input is actually a number. is_numeric would be good for that.

Link to comment
Share on other sites

Thanks for taking the time to reply, and for the great explanation - all working now :) - as i'm new i think i need to think more in terms of breaking problems down rather than bunching a solution together.

 

Have used some other forums in the past and had some quite rude responses from more capable coders - so this was very much appreciated :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.