jacktheripper
jacktheripper

Reputation: 14219

Efficient and effective form validation

I have a working example of a form here. I need to use Javascript of Jquery form validation to verify that the user has inputted his/her own data. So far I have tried to check for values, but obviously this didn't work, because the inputs and textarea already have a default value, and so the user can submit straight away without filling in anything.

Any help would be much appreciated.

Thanks in advance!

EDIT

I am using this php to send the submitted data to an email address:

<?php
$name = $_POST['name'];
if ($name=="") {
$name="Nothing was returned for this part of the form.";
}
$email = $_POST['email'];
if ($email=="") {
$email="Nothing was returned for this part of the form.";
}
$subject = $_POST['subject'];
if ($subject=="") {
$subject="Nothing was returned for this part of the form.";
}
$comments = $_POST['comments'];
if ($comments=="") {
$comments="Nothing was returned for this part of the form.";
}
$theMessage7="<b>Results from the form at www.site.co.uk/contact.html</b><br /><br />" . "Name:&nbsp;" . $name . "<br />" . "Email:&nbsp;" . $email . "<br />" . "Subject:&nbsp;" . $subject . "<br />" . "Message:&nbsp;" . $comments . "<br />";
$theEmail7="[email protected]";
$theSubject7="New form submission";
$theHeaders7="MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1
From: [email protected]
Subject: New form submission";
$theErrorFile7="www.site.co.uk/12345";
$theThanxFile7="received.html";
if (!(mail($theEmail7, stripslashes($theSubject7), stripslashes($theMessage7), stripslashes($theHeaders7)))) {
    header ( "Location: $theErrorFile7" );
        }else{
    header ( "Location: $theThanxFile7" );
}
?>

Upvotes: 1

Views: 707

Answers (2)

Vyktor
Vyktor

Reputation: 20997

The effective form of form validation on user side is to use jQuery validation plugin, see examples on proper usage.

Note: user ALWAYS can disable javascript or use some kind of bot to send invalid not checked data, so you always have to write proper server side validation.

Frameworks often provides effective way of form validation, such as Zend_Validator.

It's common to prepare method for your php application such as:

public function validate() {
  if( !isset( $_POST['name'])){
    $this->field = 'name';
    $this->msg = 'Invalid user name';
    return false;
  }

  ...
  return true;
}

And use it in both sending script:

if( $form->validate()){
  send();
}

And in check script:

$data = array();
if( $form->validate()){
  $data['status'] = 'ok';
} else {
  $data['status'] = 'failure';
  $data['field'] = $form->field;
  $data['msg'] = $form->msg;
}
echo json_encode( $data);

End than use jquery and javascript for form validation "on the fly":

<input type="text" name="name" value="" onchange="ajaxValidate();" />

function ajaxValidate(){
  // Call ajax to check script and put results
}

If you're just building small project with one form or so, you could implement few methods like:

function is_post( $key); // Shorter than write isset( $_POST[ $key])
function get_post( $key, $defaultValue); // Shorter than isset( $_POST[ $key]) ? $_POST[ $key] : $default
function is_email(...); 
...

And jQuery validation:

function validateForm() {
  $('.input').removeClass( 'error');
  var status = true;
  if( $('input[name=name]').val() == '')){
     $('input[name=name]').addClass( 'error');
     setMessage( 'Name cannot be empty');
     status = false;
  }

  ...

  return status;
}

<form onsubmit='return validateForm();' ...>

Upvotes: 3

diggersworld
diggersworld

Reputation: 13080

You could try using the HTML5 required attribute... however this will only work with browsers that support it. For example:

<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">

This will only work if you use the HTML5 doctype though.

Then for the PHP validation in the instance the HTML5 validation hasn't run due to incompatible browser... or if JavaScript doesn't run due to it being disabled/unavailable/broken.

// check input
if (empty($_POST['name']))
{
    $errors['name'] = 'Please provide your name.';
}

I then display the errors when I show the page to the user after the authentication has gone through.

<label for="name">Name:</label>
<input type="text" name="name" required="required" id="name">
<?php if (!empty($errors['name'])): ?><p class="error"><?php echo $errors['name']; ?></p><?php endif; ?>

Also... remember to protect yourself from SQL injection, XSS and mallicious code injection if this is going to be saved in a database or displayed to other users.

Upvotes: 0

Related Questions