mwktar Posted October 19, 2017 Share Posted October 19, 2017 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 Quote Link to comment https://forums.phpfreaks.com/topic/305396-easy-noob-problem-form-validation/ Share on other sites More sharing options...
requinix Posted October 19, 2017 Share Posted October 19, 2017 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 Submit 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. Quote Link to comment https://forums.phpfreaks.com/topic/305396-easy-noob-problem-form-validation/#findComment-1552826 Share on other sites More sharing options...
mwktar Posted October 19, 2017 Author Share Posted October 19, 2017 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 Quote Link to comment https://forums.phpfreaks.com/topic/305396-easy-noob-problem-form-validation/#findComment-1552827 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.