Better html form validation method

Please house,

I have this method of validating html forms form executing, but am not too sure if thats the perfect approach to it,

// here is the php code

if(isset($_POST['SubmitMyForm']) {
 
// then the validation
if(empty($_POST['hisname'])  {
echo 'Error, your name can not be blank';
return;
}
}




// then usually i like doing a separate if statement below the validation to process or execute function once is submitted

if(isset($_POST['SubmitMyForm']) {

// send data to database or log the user in or execute any function
}

For some reasons it works but i will need a more professional and secured way of doing this.

I’m not sure I understand the purpose of the second if() to check the button press - just put that code inside the first check, but don’t execute it if all the validation fails. A lot of people recommend that instead of checking for a button press, you check

if ($_SERVER['REQUEST_METHOD'] == "POST") { 

instead, but I don’t recall why.

As for the “perfect” way to do it, I can’t comment. Obviously different types of field will vary in the number of type of validation checks you need to perform.

@droopsnoot thanks for your guide, am more particular about the return i called in the if statement as a way of stopping further process.

I know i can use IF and ELSEIF for validations and then use ELSE to execute functions after validation. There fore using one isset call.

Sometimes some validation codes will be very long and confusing that is why i love splitting the two isset calls so i can know the validating part and the execution part

The recommended way to check whether the form has been submitted or not is

if ($_SERVER['REQUEST_METHOD'] === 'POST')
3 Likes

What if we have two forms in one page and how do we signify which of our forms is being checked?
Isset() showed which form is being checked

How do i know which form or form field am checking if is been posted

First you check the request method, then you check which form.

1 Like

The reason for not checking if the submit button isset() is because it won’t be set in some situations. If you have more than one possible form, a general-purpose, fool-proof way of detecting which form has been submitted is to add a hidden field with a unique value for each form. You would add logic, such as a switch/case statement, after the REQUEST_METHOD… test, to control which form processing code to execute.

As to your validation code -

  1. You should trim() all input data so that you can detect if all white-space characters were entered. You can do this for all the inputs at once using array_map(), and either use php’s trim function as the call-back, if none of the inputs are arrays, or write a recursive trim call-back function to use if any of the inputs can be arrays (once you have written this, just always use it.) This will return an array of trimmed data. You should reference elements of this returned array throughout the rest of the code.
  2. Validate all the inputs at once, storing validation error messages in an array, using the field name or another appropriate name as the array key. The reason for using the field name as the key, is so that dependent tests for a field can check if there is not already an error for that field, and so that you can test/display each error separately in the html document. This error array is also an error flag. If the array is empty, there are no errors, and you can use the input data. If the array is not empty, there are errors. You can test and display the content of this array at the appropriate location(s) in the html document.
2 Likes

@mabismad thanks for the guide, i enjoyed the array error flag alot.

Thanks

Php should have made it work exactly like isset() with a more fine tuned manner.

Please will something like this be perfect

if ($_SERVER['REQUEST_METHOD'] == "POST" && !empty($_POST['submitLogin'])){
// Start executing here
}

The use of hidden field in an html form is one thing am yet to start using, i was thinking is for bots, if i want any field hidden i better call the value in the php processing function, since i already know which value i want it to take.

This isn’t a php issue. It’s a browser issue, where the submit button may not be a ‘successful form control’ and won’t be included in the form data. Also, if the content length of the submitted post data exceeds the post_max_size setting on the web server, the web server will abort the form submission and both the $_POST and $_FILES arrays will be empty. This condition can easily occur when uploading files, but can occur for any post method form submission. By always testing first if the request method is POST, you know that a post method form was submitted and can then test for and take an appropriate action for these input conditions. If there’s only one possible form on a page, testing the request method is all you need.

Unless the ‘submitLogin’ field will always be set in the form data, this is not prefect and the test can fail to detect that the form was submitted. Using isset($_POST[‘submitLogin’]) or !empty($_POST[‘submitLogin’]) will produce the same result.

1 Like

Thanks alot @mabismad this expositions is very powerful knowing, i now understand why i must use $_SERVER[‘REQUEST_METHOD’]

Having established that fact i want to know how to work based on two forms in a page.

Yes of cause the submit value must always be set.
Let me give you what i have in mind, unless there is another mystery that will make $_SERVER[‘REQUEST_METHOD’) === ‘POST’ to be true and yet some values in the form will not be set.

If not then i think is safer to use my method above.

Let me show you the full code so you can judge.


<form action="" method="post">
<input type="text" name="country"/>
<input type="submit" name="submitLogin" value="submitLogin" />

Now here is the php code


if($_SERVER[‘REQUEST_METHOD’) === ‘POST && isset($_POST['submitLogin']) ) {

// then code goes here
}


// Please what do you think of this code? I can as well use !empty instead of isset

But i have a very strong argument, if you check the code it said run this function if this variable isset or not empty
Which means i dont tend or wish to do anything or execute any function until the submitLogin is set.

So using isset and a form fails to upload for any reason i was not wishing to process or execute empty values in the first place that was why the IF statement was called.

So the user will not get any response or feedback if his post size is higher than my post max setting, then is i will not recieve any input and he too will not get any response or feedback.

Which is exactly what will happen even if i use REQUEST_METHOD

same reactions if either is use, what do you make of my argument?

Typically you would redirect after a form is successfully posted and processed. If something goes wrong then you send the original form back along with any possible error messages:

<?php
if($_SERVER[‘REQUEST_METHOD’) === ‘POST' && isset($_POST['submitLogin']) ) {
    // Process the form
    // And redirect
    header('Location: it_worked.php');
    exit(0);
}
// Show the form and any errors
?>
<form action="" method="post">
<input type="text" name="country"/>
<input type="submit" name="submitLogin" value="submitLogin" />

This redirect or show is a fairly common pattern. It allows showing the form and processing the posted form in the same file. This might be overload for you but here is how Symfony processes forms.

1 Like

It was already mentioned depending on submit button for your code to work will completely fail in certain cases. If you have more than one form, then use a hidden form field to determine which form was sent. The problem is with type=submit. The submit button shouldn’t even have a name. It is not even part of the HTML Spec for it to have a name.

It is also naive to think that YOUR form is the only way data can be posted to your app.

Also, unless your still using HTML4, get rid of the closing slashes on the inputs.

1 Like

Thanks alot @ahundiak

I noticed you didn’t call the error codes inside the if statement neither were you using an elseif, it does makes the errors to show by default and i dont understand why.

@benanamen thanks for pointing me towards removing the closing slashes

Okay in the place that submit is not supposed to have a name i can include a hidden field and use the hidden field in my if my hidden field is not empty?

if($_SERVER[‘REQUEST_METHOD’) === ‘POST’ && !empty($_POST[‘hiddenfield’]){
// then do something