Form Validation of Multiple errors - php

What would be the best way to code for the following
To check if its empty
That its alpha
Length
I am wanting a way that I am able to combine the following if statements
Current Code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(fullName != ' ')
{
$errorfullName .= 'Please Enter Your Name';
}
}
}
if statements that need to be included:
if (!ctype_alpha(str_replace(array("'", "-"), "",$fullName))) {
$errorfullName .= '<span class="errorfullName">*First name should be alpha characters only.</span>';
}
if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
$errorfullName .= '<span class="errorfullName">*First name should be within 3-40 characters long.</span>';
}

Your are missing $ sign before fullName.Use empty function to check weather the string is empty or not. Use the below code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(empty($fullName))
{
$errorfullName .= 'Please Enter Your Name';
}
}

If you need to combine more statements, you can do it with ( if{} elseif{} else{/*NO ERROR*/}. But I think there is a smarter solution:
function valide_fulname($fullname) {
if (isset($fullName) && trim($fullName)!='')
return 'Please enter your name.';
if (!ctype_alpha(str_replace(["'", "-"], "", $fullName)))
return 'First name should be alpha characters only.';
if (strlen($fullName)<3 || strlen($fullName)>40)
return 'First name should be within 3-40 characters long.';
// no error
return false;
}
if (isset($_POST['submitButton'])) {
$error = valide_fullname($_POST['fullname']);
if (!$error)
echo "It's OK!";
else
echo '<span class="errorfullName">' . $error . '</span>';
}

Related

PHP Validation form submit

How do you stop an email being sent to you before the form is fully completed. Currently when submit is clicked even though there are validation errors present that have been picked up via the PHP checks that I have in place:
Code:
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullName'];
$myGender = isset($_POST['myGender']) ? $_POST['myGender'] : '';
$email = $_POST['email'];
$age = $_POST['age'];
$myDate = isset($_POST['myDate']) ? $_POST['myDate'] : '';
$streetNum = $_POST['streetNum'];
$streetName = $_POST['streetName'];
$city = $_POST['city'];
$state = $_POST['state'];
$postCode = $_POST['postCode'];
$movie = $_POST['movie'];
//You need to se the $var
if (empty($fullName))
{
$errorfullName .= 'Please Enter Your Name';
}
if (!ctype_alpha(str_replace(array(" ", "-"), "",$fullName))) {
$errorfullName .= 'Your name should contain alpha characters only.';
}
if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
$errorfullName .= 'First name should be within 3-40 characters long.';
}
/* Check Gender) */
if ($myGender != 'male' && $myGender != 'female') {
$errormyGender .= 'Please select your gender.';
}
/* Check Email */
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$erroremail .= 'Enter a valid email address.';
}
/* Age */
if (intval($age) == '') {
$errorage .= 'Please enter your current age';
}
if (intval($age) < 3 OR intval($age) > 200){
$errorage .= 'Age must be less than 200 years';
}
if(intval($age) == "/^[0-9]$/" ){
$errorage .= 'Must be numeric numbers';
}
/* check date using explode (breaks a string into an array.)if day is not 1-31, throw error*/
if(empty($myDate))
{
$errormyDate.= 'Please enter a current date';
}
$date_arr = explode ("-", $myDate);
$dateSplit = array_slice($date_arr, 0,1);
$dateYear = current($dateSplit);
if($dateYear > date('Y'))
{
$errormyDate .= 'Sorry your not born in the future';
}
/* Check Address House Number if its not numeric, throw error */
if (intval($streetNum) == '') {
$errorstreetNum .= 'Please add street Number';
}
/* Street Name */
if (strlen($streetName) < 3 OR strlen($streetName) > 200) {
$errorstreetName .= 'Street must be filled out and within 200 characters';
}
/*City Name */
if (strlen($city) < 3 OR strlen($city) > 200) {
$errorcity .= 'City must be filled out and within 200 characters';
}
/*State Name */
if (strlen($state) < 3 OR strlen($state) > 200) {
$errorstate .= 'State must be filled out and within 200 characters';
}
/* Check postCode */
if(intval($postCode) == "/^[0-9]$/" ){
$errorpostCode .= 'Post Code must be numeric numbers';
}
/* Check movie selection */
if (trim($movie) === "select") {
$errormovie .= 'Please select a favourite movie';
}
if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){
echo '$errorsuccess .= 'Please complete all sections of the form'';
}
else {
$success = "Thank you for submitting your form; We will be in contact soon";
//send mail
$to = "#yahoo.co.nz";
$subject = "Php form data";
$message = "<p>".$fullName."</p><p>".$myGender."</p><p>".$email."</p><p>".$age."</p><p>".$myDate."</p><p>".$streetNum."</p><p>".$streetName."</p><p>".$city."</p><p>".$state."</p><p>".$postCode."</p><p>".$movie."</p>";
$from = "#yahoo.co.nz";
mail($to,$subject,$message);
}
}
The reason being is that you even though you have several validations completed in the above, none of them are later checked to see if they failed/passed, your only sanity check is here:
if ($fullName, $myGender, $email, $age, $myDate, $streetNum, $streetName, $city, $state, $postCode, $movie, == " "){
Which its self is pretty useless all together, by the way.
A simpler way for this would be to first create an array to hold all the errors.
$errors = array();
Then when you do your individual checks, make them a key, for example:
if (empty($fullName))
{
$errors['fullname'] .= 'Please Enter Your Name';
}
And
if (intval($age) == '') {
$errors['age'] .= ' Please enter your current age.';
}
if (intval($age) < 3 OR intval($age) > 200){
$errors['age'] .= ' Age must be less than 200 years.';
}
if(intval($age) == "/^[0-9]$/" ){
$errors['age'] .= ' Must be numeric numbers.';
}
Then later you can do:
if($errors){
echo 'There are errors in the form. Please observe each of the errors and try again.'. PHP_EOL;
foreach($errors as $idx => $error){
echo ucfirst($idx). ': ' .$error;
}
}
Set something like $err to false at the beginning of the code. Set it to true when an error is detected. (Even if it's already true; just setting it is easier than checking.)
Then, you can condition the final result on $err.
It looks like that in order to send the email, you only need to have a value for each of your input fields (from $fullName to $movie).
Where you are validating the form (for example, when you use if (empty($fullName))..., the error that is produced if the form isn't filled out correctly always differs. Unless you have some kind of reason for this, I would just stick to a generic error variable of $formerror.
Then in the final section of your code, where you use if($fullName...$movie == ''), you could change this to if($fullName...$movie === '' AND !empty($formerror)) so that if any errors were picked up during the validating of the form, you would be able to echo $formerror and if not, the email would send.

PHP - Check if one of two form fields is filled?

My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.

email validation in php

I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}

preg_matchvalidation

Okay, everything I've checked on this site referring to validation isn't what I'm looking for.
What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";
}
if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";
}
I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?
I do know it's something to do with
if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))
In doing this I tried to do
if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {
But that also gave me an error :/
Could anyone give me a solution for this?
Thanks!
UPDATE:-
Nvm, I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname. :)
Why don't you just use strlen() to get the string length, and then test it against your limits ?
$length = strlen($nick);
if ($length > 3 AND $length < 16) {
//Do STuff
} else {
//Do stuff for failed requirement
}
I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3>You must enter between 4 and 15 characters!</h3> </center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname.

Multiple conditions in PHP

I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>

Categories