[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Validate a forms required fields

Posted on 2012-08-16
36
Medium Priority
?
541 Views
Last Modified: 2012-08-16
Hi,

Could somebody please help me with this.  I have a form with a few fields on it which i would like to be required.  How do i script this so that a user is alerted if they do not enter any information in these fields?

<div id="footerFormWrapper">
		<h3>Please fill in the form below.</h3>
		
<form action="/s2form/process.php"" name="WebToLeadForm" method="post" id="WebToLeadForm" accept-charset="utf-8">
			
<fieldset>
<label class="field-first">First Name &#42;<input type="text" name="first_name" value="" id="first_name" /></label>

<label class="field-last">Last Name &#42;<input type="text" name="last_name" value="" id="last_name" /></label>

<label class="field-company">Company &#42;<input type="text" name="company" value="" id="company" /></label>

<label class="field-email">Email &#42;<input type="text" name="email" value="" id="email" /></label>

<label class="field-phone">Phone &#42;<input type="text" name="phone" value="" id="phone" /></label>

</fieldset>
<input type="submit" value="Send" class="button" name="Submit"/>
</form>
</div>

Open in new window


Thanks
0
Comment
Question by:anthonytr
  • 17
  • 14
  • 4
  • +1
36 Comments
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38300971
There are two methods

client side using Javascript
server side where you check the information posted back and regenerate the form with errors.

I am assuming you want a client side validation

for the fields that require valiation give them a class="required-field"

Add JQuery to your form example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Add the following script
$(function() {
  $('#WebToLeadForm').submit(function () {
    var result = true;
    $('.required-field').each(function() {
      if ($(this).val() == '') {
           alert('Field ' + $(this).attr('name') + ' is required');
           result = false;
      }
    });
    return result;
  });
});

Open in new window

0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 38301002
For good browsers that support HTML5 you can added the property required="required" and the browser will pop up a message if the user tries to submit without filling in the input.

For junk browsers (IE) you need to code a validation check either on the server or with Javascript.  I prefer server side for security reasons.  Wth PHP you can use:

if (!isset($_POST['first_name']
{
   // set some kind of error indicator or message for the response.
}

To do it with javascript you need to code an event handler off the submit button and test with:
if (document.forms[0].first_name.value=="")
{
  //some error handling here.
}


Cd&
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38301008
The client side validation is useful to give the user an immediate sense of what he's requested to do, but never trust client validation only! Javascript could be disabled and in that case your validation code would be simply not executed.

For server-side validation write something like this in process.php:
  $required = array("first_name", "last_name", "company", "email", "phone");
if(isset($_POST['Submit'])){
  foreach ($_POST as $k=>$v) {
    if(($v == '') && in_array($k, $required)){
      echo "Please, don't leave $k field empty!<br>";
    }
  }
}
?>

Open in new window


Obviously, you cann enhance this little script as you wish, but the basic, needed code is this.

Cheers
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301018
Here is a full code example showing two types of error - message box and in form error
<?php
if (isset($_GET['aaa'])){
  setcookie ('contactform', "", time()-3600);
  unset($_COOKIE['contactform']);
}
?>
<!doctype html>
<html>
<head>
<title>EE Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
.error {
  color: red;
}
</style>
<script type="text/javascript">
$(function() {
  $('#WebToLeadForm').submit(function () {
    var result = true;
    $('.required-field').each(function() {
      if ($(this).val() == '') {
           alert('Field ' + $(this).attr('name') + ' is required');
       // or
       $(this).next('div.error').html('required field');
           result = false;
      }
    });
    return result;
  });
});
</script>
</head>
<body>
<div id="footerFormWrapper">
    <h3>Please fill in the form below.</h3>
    
<form action="/s2form/process.php"" name="WebToLeadForm" method="post" id="WebToLeadForm" accept-charset="utf-8">
      
<fieldset>
  <div>
    <label class="field-first">First Name &#42;</label><input type="text" name="first_name" value="" id="first_name" class="required-field"/><div class="error"></div>
  </div>
  <div>
    <label class="field-last">Last Name &#42;</label><input type="text" name="last_name" value="" id="last_name" />
  </div>
  <div>
    <label class="field-company">Company &#42;</label><input type="text" name="company" value="" id="company" />
  </div>
  <div>
    <label class="field-email">Email &#42;</label><input type="text" name="email" value="" id="email" class="required-field"/><div class="error"></div>
  </div>
  <div>
    <label class="field-phone">Phone &#42;</label><input type="text" name="phone" value="" id="phone" />
  </div>
</fieldset>
<input type="submit" value="Send" class="button" name="Submit"/>
</form>
</div>
                                  
</body>
</html>

Open in new window

0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301031
We are assuming (s)he is using PHP ....
0
 

Author Comment

by:anthonytr
ID: 38301113
Hi All,

Thanks for the amazing response top the questsion.  I have a few extra questions.  I totally understand the need for server side of client side (java being disabled etc).  As you can see from my code, the form data is submitted to /s2form/process.php.  This is a 3rd party script that adds forms data into a Highrise CRM account.

This is the contents of the process.php file

require_once('functions.php');
if ($use_captcha) {
	$check_captcha = check_captcha($_POST);
}
//attempt to add the contact information to highrise
$add_contact = add_contact();
//send mail if enabled
if ($conf['use_email'] == true) {
  //send email to client if turned on
  if ($send_email_to_contact == true) {
  	$send_contact_email = send_contact_email();
    $message = $send_contact_email;
  }else{
    $message = $add_contact;
  }
  //send confirmation email to self
  if ($send_email_to_self == true) {
    $send_self_email = send_confirm_email($message);
  }
}
//redirect to successful submit page
header('Location: '.$success_redirect);
?>

Open in new window


where would I add the validation script?

Thanks
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301211
require_once('functions.php');
if ($use_captcha) {
	$check_captcha = check_captcha($_POST);
}
//
// VALIDATE HERE - assume setting $data_is_valid TRUE / FALSE based on validation success
//
if ($data_is_valid) {
//attempt to add the contact information to highrise
$add_contact = add_contact();
//send mail if enabled
if ($conf['use_email'] == true) {
  //send email to client if turned on
  if ($send_email_to_contact == true) {
  	$send_contact_email = send_contact_email();
    $message = $send_contact_email;
  }else{
    $message = $add_contact;
  }
  //send confirmation email to self
  if ($send_email_to_self == true) {
    $send_self_email = send_confirm_email($message);
  }
}
//redirect to successful submit page
header('Location: '.$success_redirect);
}
// ASSUMING that if you drop through to here your form will be displayed again
// In the code that displays the form you are going to need to set the values
// of each form element and error message if required

Open in new window

0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38301287
Where $data_is_valid is set?
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38301300
It seems $data_is_valid is a global variable set in check_captcha() function: if so the code will be
require_once('functions.php');
if ($use_captcha) {
  $check_captcha = check_captcha($_POST);
}
//
// VALIDATE HERE - assume setting $data_is_valid TRUE / FALSE based on validation success
//
if ($data_is_valid) {
$required = array("first_name", "last_name", "company", "email", "phone");
if(isset($_POST['Submit'])){
  foreach ($_POST as $k=>$v) {
    if(($v == '') && in_array($k, $required)){
      echo "Please, don't leave $k field empty!<br>";
    }
  }
  exit();
}
//attempt to add the contact information to highrise
$add_contact = add_contact();
//send mail if enabled
if ($conf['use_email'] == true) {
  //send email to client if turned on
  if ($send_email_to_contact == true) {
  	$send_contact_email = send_contact_email();
    $message = $send_contact_email;
  }else{
    $message = $add_contact;
  }
  //send confirmation email to self
  if ($send_email_to_self == true) {
    $send_self_email = send_confirm_email($message);
  }
}
//redirect to successful submit page
header('Location: '.$success_redirect);
}

Open in new window


Cheers
0
 

Author Comment

by:anthonytr
ID: 38301301
Is it possible to have a popup message box informing the user of an error?  This is all new to me.  I don't mind having the error displayed on the form, just dont know how i would code that into the form itself.

Thanks Julian for your answer, it has, however, confused me even more... :)

What do you mean by $data_is_valid TRUE / FALSE ?

Anthony
0
 

Author Comment

by:anthonytr
ID: 38301326
Hi marqusG

I did impliment your code sugestion, however, when i submit the form it sends me to a blank screen : http://www.archiveservices.co.uk/s2form/process.php

Anthony
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301335
Sorry The $data_is_valid - represents the result from doing your validatation - whatever that is. In other words if all fields validate ok then  you would set that to True and you would process the rest of the script as it stands.

If False you would need to return the visitor to the form and display the error.

The question you are asking is quite a bit beyond to the original question posted. You are essentially looking for a total validation cycle which would be

Display Form
Check locally for errors (javascript)
Post to server
Validate data on server
If data is not valid
   set error conditions and return to form
   populate form with data already submitted
   display errors (form based or popup)
else
  process valid information
endif

A popup is possible but again requires javascript and placing javascript code in the page when it is redrawn. If you want a proper validation cycle that is immune to javascript being on or off you will still need to display the errors in the form.

There are two ways of doing this as well
1) As a block showing all errors in a single block - usually a div before the form - this is the easiest
2) Next to each field - more elegant and informative but a little bit more coding
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 38301353
Sorry: you have to set form action to "/s2form/process.php": I posted code I used to test solution but in my server I had to change the action to index.php! Please, use the code setting the action form to "/s2form/process.php" and you'll see it'll works. lol

Cheers
0
 
LVL 60

Accepted Solution

by:
Julian Hansen earned 2000 total points
ID: 38301377
Here is one way of doing it.

require_once('functions.php');
if ($use_captcha) {
	$check_captcha = check_captcha($_POST);
}
// call a function to validate the data
// if the returned array is empty there were no errors
// in which case continue process valid data
$errors = array();

// check to see if the form is posting back - only validate if it is

if (!empty($_POST['Submit'])) 
  $errors = validate_form();
if (empty($errors) {
//attempt to add the contact information to highrise
$add_contact = add_contact();
//send mail if enabled
if ($conf['use_email'] == true) {
  //send email to client if turned on
  if ($send_email_to_contact == true) {
  	$send_contact_email = send_contact_email();
    $message = $send_contact_email;
  }else{
    $message = $add_contact;
  }
  //send confirmation email to self
  if ($send_email_to_self == true) {
    $send_self_email = send_confirm_email($message);
  }
}
//redirect to successful submit page
header('Location: '.$success_redirect);
}
// If there was an error - or this is the first time the form is displaying
show_form();

function & validate()
{
   $errors = array();
   // change messages as required
   if (empty($_POST['first_name')) $error['first_name'] = 'This is a required field';
   if (empty($_POST['email')) $error['first_name'] = 'This is a required field';
   // do other validation here
   return $errors;
}

function showform($errors)
{
   // output the form here
?>
<div id="footerFormWrapper">
		<h3>Please fill in the form below.</h3>
		
<form action="/s2form/process.php"" name="WebToLeadForm" method="post" id="WebToLeadForm" accept-charset="utf-8">
			
<fieldset>
<label class="field-first">First Name &#42;</label>
<input type="text" name="first_name" value="<?php echo empty($_POST['first_name']?'':$_POST['first_name'];?>" id="first_name" /><div class="error"><?php echo empty($errors['first_name'])?'':$errors['first_name'];?>

<label class="field-last">Last Name &#42;</label><input type="text" name="last_name" value="<?php echo empty($_POST['last_name']?'':$_POST['first_name'];?>" id="last_name" />

<label class="field-company">Company &#42;</label><input type="text" name="company" value="<?php echo empty($_POST['first_name']?'':$_POST['company'];?>" id="company" />

<label class="field-email">Email &#42;</label><input type="text" name="email" value="<?php echo empty($_POST['first_name']?'':$_POST['email'];?>" id="email" /><?php echo empty($errors['first_name'])?'':$errors['first_name'];?>

<label class="field-phone">Phone &#42;</label><input type="text" name="phone" value="<?php echo empty($_POST['first_name']?'':$_POST['phone'];?>" id="phone" />

</fieldset>
<input type="submit" value="Send" class="button" name="Submit"/>
</form>
</div>
                                  
<?php
}
?>

Open in new window

Not perfect but gives the general idea.
0
 

Author Comment

by:anthonytr
ID: 38301425
Hi Julian,

i have tried your code, but when i press send on my form i just get a blank screen.
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301487
Yes - my code needs to be modified for your environment - you have not posted all the code that you are using so you need take what I have posted and fit it around your setup - I had to guess what your setup looked like.

Also you will see line 14 has a missing closing ')'

if (empty($errors) {
should be
if (empty($errors)) {

But there may be other errors.

If you want a full solution then we need to see all the code.
0
 

Author Comment

by:anthonytr
ID: 38301545
The only code i have (or know of which is being used) is:

Process.php

require_once('functions.php');
if ($use_captcha) {
	$check_captcha = check_captcha($_POST);
}
//attempt to add the contact information to highrise
$add_contact = add_contact();
//send mail if enabled
if ($conf['use_email'] == true) {
  //send email to client if turned on
  if ($send_email_to_contact == true) {
  	$send_contact_email = send_contact_email();
    $message = $send_contact_email;
  }else{
    $message = $add_contact;
  }
  //send confirmation email to self
  if ($send_email_to_self == true) {
    $send_self_email = send_confirm_email($message);
  }
}
//redirect to successful submit page
header('Location: '.$success_redirect);
?>
                                            

Open in new window


And my form:

<div id="footerFormWrapper">
		<h3>Please fill in the form below.</h3>
		
<form action="/s2form/process.php"" name="WebToLeadForm" method="post" id="WebToLeadForm" accept-charset="utf-8">
			
<fieldset>
<label class="field-first">First Name &#42;<input type="text" name="first_name" value="" id="first_name" /></label>

<label class="field-last">Last Name &#42;<input type="text" name="last_name" value="" id="last_name" /></label>

<label class="field-company">Company &#42;<input type="text" name="company" value="" id="company" /></label>

<label class="field-email">Email &#42;<input type="text" name="email" value="" id="email" /></label>

<label class="field-phone">Phone &#42;<input type="text" name="phone" value="" id="phone" /></label>

</fieldset>
<input type="submit" value="Send" class="button" name="Submit"/>
</form>
</div>
                                 

Open in new window


Anthony
0
 

Author Comment

by:anthonytr
ID: 38301564
Sorry, and the following functions.php file.
functions---Copy.txt
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301611
Ok so this is part of Highrise then?

There might be a specific way of doing this in Highrise which if we use the above may not be the right solution.

I am not familiar with Highrise. Might be a good idea to give the guys at 37Signals a shout.
0
 

Author Comment

by:anthonytr
ID: 38301667
No it's not highrise, it is a third party form processing script.

Highrise is the end CRM where the data is added, but the form is not controlled or designed by Highrise or 37Signals.
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301741
So if I understand this correctly then you are posting the form back to the third party code?

Is your form sitting in a standard html file then - how do you get to the form is it a link to an html file or do you have script playing a role in it being displayed?

I am trying to get a handle on the process flow from link to form to processing script (I think I have the latter sorted out - but need to know the first bit because if you are vaildating you need to be able to go back to the form with errors and data).
0
 

Author Comment

by:anthonytr
ID: 38301907
From what i can see/understand, yes the form data is posted back to the 3rd party code.  My form is simple created in a standard html file with the "action" part pointing to the process.php file (3rd party script).  It is this script and accosicated files which then takes the data which has been passed via the process.php script to our Highrigh account.

What i'm trying to do is make sure that required fields are supplied.  At present, if i just submit the form without entering any information on the form, i get forwarded to my thank you page and i later receive an email saying that not enough information was submitted on the form and therefore the highrise account was not created.

Perhaps client side would be the easiest method here - i just thought i could alter the process.php and functions.php file to catch this before it was submitted.

continued thanks,

Anthony
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38301977
You can but if the validation fails you have to route back to your form and to avoid annoying the people filling it out you will have to then populate the form with the data they have already input.

give a couple minutes to play with it - see what I can come up with.
0
 

Author Comment

by:anthonytr
ID: 38302030
That's very kind - thank you
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302112
Ok this should do it - just change the action in the form - I changed it for my local server.
process.php
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302150
and here is a version that also has the JScript validation. I purposefully left off the last two fields from the JScript so you can see that if those fields are empty they are caught in the post back.
process.php
0
 

Author Comment

by:anthonytr
ID: 38302151
Hi,

Really stupid question here.  Does the attached file contain both the updated Process.php script and the seperate form html which i need to update my existing form with?
0
 

Author Comment

by:anthonytr
ID: 38302225
After updating the script/code the form went from this:
Old Form layout
to this:
New form layout
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302274
Yes - it is an all in one - so you replace your existing process.php with that and loose your form instead point to process.php to display the form.
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302283
That's because I put styling into the form - the code you posted did not have styling.

You can edit the form in process.php and make it so that it works with your styling.
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302364
With your original formatting back in -
process.php
0
 

Author Comment

by:anthonytr
ID: 38302531
hi

sorry, when you say "point to process.php to display the form" what do you mean?
0
 

Author Comment

by:anthonytr
ID: 38302548
my styling is on a seperate css file
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302568
It is a bit of challenge trying to explain how to do this without being able to see how things are implemented on your side. I am providing you with solutions to specific problems but you are going to need to look on your side as to how to adapt them to your specific needs.

You said earlier your html is in a separate page. I took that to mean a self contained page with doctype, head, body etc

From what you are saying now this is not the case - if your styling is in a separate file how is it currently getting into your form. You need to apply that same method to the code I sent you - and potentially massage the process.php to do what you need it to.

Process.php provides an example of how to do server side and client side validation - but you will need to bend it to fit your site.
0
 

Author Comment

by:anthonytr
ID: 38302610
ok - i will ork through the files you sent and see how i can impliment them on my site.

Thank you for all your help

Anthony
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38302692
If you get stuck post back and I will do what I can to assist - just a bit difficult when I can't see the whole picture.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month20 days, 3 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question