Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Thursday 28 March 2019

Yii first models and forms

This is partly based on the documentation found at https://www.yiiframework.com/doc/guide/2.0/en/start-forms

Model

In building a form interaction it's often best to begin with a model; a place where the data will be sent for checking, and or converting and putting into a source. A model is therefore also required far all CRUD operations.

rules and validate

The model below handles an entry form post. It doesn't do much with the data, but it does contain a method with a reserved word, rules(). This method will be called later from the controller using the term validate()

The rules method return to the validate call within the controller validation of 2 expectations:

  1. That the name and emailAddress fields are required.
  2. That the emailAddress is a valid email field.

<?php
namespace app\models;
use Yii;
use yii\base\Model;
class EntryForm extends Model
{
    public $name;
    public $emailAddress;
    public function rules()
    {
        return [
            [
              ['name', 'emailAddress'], 'required'
            ],
            [
              'emailAddress', 'email'
            ]
        ];
    }
}

Controller

The controller makes our newly created model available to us through the line
use app\models\EntryForm;
A method is created called actionEntry() is created which will be called from the form (contained in a view) using the view file name of entry.php
and a new instance of the model is created through the line
$model = new EntryForm();
The POSTed data is sent to the model using the
Yii::$app->request->post() method. A list of other request options can be found at
https://www.yiiframework.com/doc/api/2.0/yii-web-request
At the same time, the model validates the data using
$model->validate() which as mentioned previously makes use of the rules() method.
Once these tests have been passed and you've done something useful with the data, you can render the confirmation view, entry-confirm.php.
If something went wrong you can take the user back to the form view entry.php.
In both cases, though it may seem a little confusing, $model is passed as 'model' to the views. This means that 'model' becomes $model within the views.
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Request;
use app\models\EntryForm;
class SiteController extends Controller
{
    // actionIndex(), actionSay() etc.
    public function actionEntry()
    {
        $model = new EntryForm();
        $request = new Request();
        if ($model->load($request->post()) && $model->validate()) {
            // valid data received in $model do something meaningful here
            return $this->render('entry-confirm', ['model' => $model]);
        } else {
            // either the page is initially displayed or there is some validation error
            return $this->render('entry', ['model' => $model]);
        }
    }
}

Views

As mentioned in the controller section above, there are 2 views; entry.php and entry-confirm.php.

entry-confirm.php

Residing at views/site/entry-confirm.php is fairly easy to understand.
<?php
use yii\helpers\Html;
?>
<p>You have entered the following information:</p>
<ul>
    <li><label>Name</label>: <?php echo Html::encode($model->name); ?></li>
    <li><label>Email</label>: <?php echo Html::encode($model->emailAddress); ?></li>
</ul>

entry.php

Residing at views/site/entry.php requires a little more explanation.
The ActiveForm::begin() method creates form tag. This tag has an action field into which the ActiveForm::begin() method the filename of the form. This action field is used to make a request to the actionEntry() method in the controller.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
    <?php echo $form->field($model, 'name'); ?>
    <?php echo $form->field($model, 'emailAddress'); ?>
    <div class="form-group">
        <?php echo Html::submitButton('Submit', ['class' => 'btn btn-primary']); ?>
    </div>
<?php ActiveForm::end(); ?>

Wednesday 10 August 2016

Using jQuery FormData to include files when making POST request

In this example I create a form, with a text, and file input field. When I submit the form, contents from all input fields are submitted through the 'FormData' class. The results from the called script are returned to a div. Finally, the fields are then cleared.
<html>
<head>
    <title>jQuery File Upload</title>
</head>
<body>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
        <input type="text" name="myname" />
        <input type="file" name="fileinfo" multiple="" />
        <button type="submit">Submit</button>
    </form>
    <div id="result"></div>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script>  
    (function()
    {
        $('form').on('submit', function(e)
        {
            var theDiv = $('div#result');
            var thisForm = $(this);
            var action = thisForm.attr('action');
            var method = thisForm.attr('method');
            $.ajax(
            {
                url: action,
                type: method,
                data: new FormData(this),
                processData: false,
                contentType: false
            }).done(function(datareceived)
            {
                thisForm.find('input, textarea').val('');
                theDiv.html(datareceived);
            });
            e.preventDefault();
        });
    })();
    </script>
</body>
</html>

To test if it works I use upload.php. See
<?php
$str = NULL;
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $file['name']) == FALSE)
    {
        $str .= $file['name'].' not uploaded<br />';
    }
}
$str .= '<br />POST items include : <br />';
foreach($_POST as $postitem => $value)
{
    $str .= 'Name : '.$postitem.' Value : '.$value.'<br />';
}
echo $str;
?>

Wednesday 23 March 2016

jQuery plugin which takes and receives form data

This jQuery plugin to take all form data, pass it to a named script and return a message to a named HTML element. Particularly good with Twitter Bootstrap.
See the code here.

Wednesday 10 June 2015

Bootstrap formhandler calling class methods with JSON returned and processed

This entry offers a number of techniques through 4 files.

  • index.php contains a message alert which will only be displayed when there is a message to put in it. The forms use an action which contains the name of a class and method which will be used to process the results. There is also a call to custom.js
  • custom.js handles the form submissions and delivers the data returned to the page. It passes the form action and field content to formhandler.php. It receives JSON which then is either passed to a message alert or a data table.
  • formhandler.php receives the call from custom.js. This contains the form action and field content. It takes the form action and uses them to create calls to classes and methods named in the form action. For example and action of myclass/mymethod would be used to create calls similar to those below. The inclusion of the $_POST array allows the form field content to be passed to the class. The data returned is then passed back to custom.js for processing.
$myclass = new myclass($_POST);
$myclass->mymethod;

  • myclassname.class.php contains the example class and methods. The class receives the $_POST array and processes its content. There are 3 methods which demonstrate how to return a string, an array and an object.

This approach is a quick way of utilising many classes. It does not require a .htaccess file to simplify form actions and is flexible in its handling of returned data through JSON.
Have fun.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form handler for many PHP classes using jQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
    body
    {
      margin-top:2em;
    }
    #message, #data-table
    {
      display:none;
    }
    </style>
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <div id="message" class="alert alert-success" role="alert"></div>
          <!-- <form action="myclassname/myclassmethod_string" method="POST"> -->
          <!-- <form action="myclassname/myclassmethod_array" method="POST"> -->
          <form action="myclassname/myclassmethod_object" method="POST">
            <div class="form-group">
              <label for="name"></label>
              <input type="text" name="name" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <table id="data-table" class="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="custom.js"></script>
  </body>
</html>

custom.js

(function()
{
  $('form').on('submit', function(event)
  {
    $.post('formhandler.php?action='+$(this).attr('action'), $(this).serialize(), function(data)
    {
      var json_obj = JSON.parse(data);
      if(json_obj.hasOwnProperty('message'))
      {
        $('#message').text(json_obj.message);
        $('#message').show();
        $('#message').fadeOut(3000);
      }
      else
      {
        $.each(json_obj, function(name,age)
        {
          $('#data-table > tbody').appendRow(name,age);            
        });
        $('#data-table').show();
      }
    });
    event.preventDefault();
  });
})();

$.fn.appendRow = function()
{
  var s = '<tr>';
  for (var i = 0; i < arguments.length; i++)
  {
    s += '<td>'+arguments[i]+'</td>';
  }
  s += '</tr>';
  return $(this).append(s);
}

formhandler.php

<?php
if(isset($_GET['action']))
{
$arr = split('/', $_GET['action']);
$class = $arr[0];
$method = $arr[1];
require_once $class.'.class.php';
if(class_exists($class))
{
$evalStr = '$'.$class.' = new '.$class.'($_POST);';
eval($evalStr);
if(method_exists($class, $method))
{
$evalStr = '$returnValue = $'.$class.'->'.$method.'();';
eval($evalStr);
}
else
{
$returnValue = 'Method does not exist';
}
}
else
{
$returnValue = 'Class does not exist';
}
}
else
{
$returnValue = 'No action given';
}

if(is_object($returnValue) || is_array($returnValue))
{
echo json_encode($returnValue);
}
else
{
$returnArr = array('message'=>$returnValue);
echo json_encode($returnArr);
}
?>

myclassname.class.php

<?php
class myclassname
{
private $pa;
function __construct($postArray = array())
{
$this->pa = $postArray;
}

function myclassmethod_string()
{
return 'Your name is '.$this->pa['name'];
}

function myclassmethod_array()
{
$myArr = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myArr;
}

function myclassmethod_object()
{
$myObj = (object) array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myObj;
}

function __destruct()
{

}
}
?>

Tuesday 10 February 2015

Using Font Awesome icons and jQuery to show form loading in Twitter Bootstrap page

Font Awesome is a really useful tool for adding icons to your website. It also comes with animated icons which can be used to show when your form is waiting for a response. In the example below, I have created a basic Twitter Bootstrap page. The page has a form. When the form is submitted, there is a delay in its response. During the delay, I use jQuery to show a Font Awesome animated icon.
First the Twitter Bootstrap page with the differences in red:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Font Awesome Animated Icons</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">   
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
  <i class="fa fa-circle-o-notch fa-spin"></i>  
  <form action="response.php" method="POST">
    <input type="text" name="yourname" id="yourname" placeholder="Enter your name" />
    <button type="submit">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script>
  (function()
  {
    var thisForm = $('form');
    var i = $('i');
    i.hide();
    thisForm.submit(function()
    {
      i.show();
      thisForm.hide();
      $.post(thisForm.attr('action'),thisForm.serialize(), 
      function(data)
      {
        thisForm.empty().html(data);
        i.hide();
        thisForm.show();
      });  
      return false;
    });
  })();
  </script>
  </body>
</html>
Now my response.php
<?php
sleep(2);
echo 'Hello '.$_POST['yourname'];
?>

Friday 9 August 2013

Automatically log users into your website using HTML5 Local Storage

So your users has been registered. They have gone through the pain of logging in on a mobile phone and you want them to authenticate more easily next time round, so that they don't give up on using your web app.

The solution : HTML5 Local Storage. In the code below, I take the username and password, and put them in localstorage variables. When the (login) page is visited again, I check to see if those localstorage variables exist. If they do, I add them as values to the username and password field, and perform a submit.

Enjoy!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HTML5 Save Password</title>
<!--[if IE]>
<script src="html5.js"></script>
<![endif]-->
<script src="jquery.min.js"></script>
</head>
<body>
<form method="POST" action="set.php">
<label for"username">Username</label>
<input name="username" type="email" />
<label for"password">Password</label>
<input name="password" type="password" />
<input type="submit" />
</form>
<script>
(function()
{
u = false;
p = false;
if(localStorage.getItem('username') != null)
{
$('form input[name=username]').val(localStorage.getItem('username'));
u = true;
}
if(localStorage.getItem('password') != null)
{
$('form input[name=password]').val(localStorage.getItem('password'));
p = true;
}
if((u == true) && (p == true))
{
$('form').submit();
}
$('form').submit(function()
{
localStorage.username = $('form input[name=username]').val();
localStorage.password = $('form input[name=password]').val();
});
})();
</script>
</body>
</html>

Friday 12 July 2013

Form changer jQuery plugin

Websites I work on often include the need to add a login, password reset and self-registration form. This requirement can either take up too much space on the page, or require a refresh to load each form. They could all easily be put in a container like a div and called upon (or shown) only when needed. This is what I've done with the example below.
The 'data-location' anchor attributes must correspond to the form ID's they are requesting.
First, I've hidden all the things not required to be visible on load and just spaced the links out (in blue).
Second, I've created the container, forms and links I need (in red).
Third, I've called my plugin to handle the interaction (in green).
Below the HTML, I present the plugin code. There is a little catch all at the top, just in case anyone creates a container with either an ID, class or neither.
Enjoy!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form changer</title>
<style>
#formholder #resetpassword, #formholder #selfregister, #formholder a[data-location="login"]
{
display:none;
}
#formholder a
{
margin:0.2em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<div id="formholder">
<form id="login">
<p>Hello from login</p>
</form>
<form id="resetpassword">
<p>Hello from reset password</p>
</form>
<form id="selfregister">
<p>Hello from self-register</p>
</form>
<a href="#" data-location="login">Login</a><a href="#" data-location="resetpassword">Reset password</a><a href="#" data-location="selfregister">Self-register</a>
</div>
<script src="formchanger.plugin.js"></script>
<script>
(function()
{
$('#formholder a').formchanger();
})();
</script>
</body>
</html>

Now the plugin code:
(function($)
{
$.fn.formchanger = function()
{
id = $(this).parent().attr('id');
clas = $(this).parent().attr('class');
tag = $(this).parent().get(0).tagName;
if(id != null)
{
container = '#'+id;
}
else if(clas != null)
{
container = '.'+clas;
}
else
{
container = tag;
}
anchors = $(container).children('a');
forms = $(container).children('form');
$(this).click(function()
{
$(anchors).show();
$(forms).hide();
$(container+' #'+$(this).data('location')).show();
$(this).hide();
});
};
})(jQuery);

Monday 27 June 2011

PHP Form, jQuery, working in IE

Some days, you start by saying, "'I'll just get this out of the way, then I can concentrate on something heavier". You then write code without testing because you know how it works, and apart from a little syntax change, you get it working fine. About 15 minutes. This was my experience with writing a page with a form. It stored the data in a text file, then updated the page tag with the new contents. It worked fine in Chrome and Firefox. Then the dreaded IE pulled me back. 3 hours later, I find the solution. Below are code examples to a common problem.
Create a html form.
On submission, write the contents of the form to a file.
Once the file has been updated, refresh a section showing the new content.

Here is the code for readdata.php. Notice the @ before file_get_contents. This suppresses a warning if the file does not already exist.

<?php
foreach (explode("\n", @file_get_contents('data.data')) as $value)
{
echo $value."<br />";
}
?>
Here is the code for writedata.php. Nothing particularly clever here.

<?php
file_put_contents('data.data', $_POST['stuff']."\n", FILE_APPEND);
?>
Now to the main page. A few of important items here:
  1. Only $.get works in IE .load doesn't.
  2. $.ajaxSetup({cache: false}) is also required for IE otherwise you get all sorts of content varients coming through.
  3. I used the jQuery Form Plugin from http://jquery.malsup.com/form/ It saves a lot of problems.


Have fun.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Read and write using jquery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$.fn.readStuff = function()
{
$.get('readdata.php', null, function(data)
{
    $('section').html(data);
});
$('#stuff').val('');
}
$(document).ready(function()
{
$.ajaxSetup({cache: false});
$('form').ajaxForm(function()
{
$(this).readStuff();
});
});
</script>
</head>
<body>
<h1>PHP and jQuery read/write test</h1>
<h2>Write data</h2>
<form action="writedata.php" method="POST">
<input type="text" name="stuff" id="stuff" />
<input type="submit" />
</form>
<h2>Read data</h2>
<section>
<?php
include 'readdata.php';
?>
</section>
</body>
</html>

Tuesday 8 February 2011

Submit Form with Loader

I achieve 2 objectives with the form below.

The first is that I use jQuery to capture the user hitting the enter key after adding the password. By using jQuery, this works in all browsers.

The second thing I deliver is a 'loading...' image when the form has been submitted. It stays there until we have a result from the target PHP script, authenticate.php. Your authenticate.php could look something like this
<?php
echo 'Who are you?';
?>

You could also pass parameters to the PHP and do it properly. See http://effectivewebdesigns.blogspot.com/2010/10/send-form-information-to-php-through.html

BTW, you'll also have to create your own loading.gif

See demo.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<title>Submit Form with Loader</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
$('#pass').keyup(function(event)
{
if(event.keyCode == 13)
{
$("#sub").click();
}
});
$('#sub').click(function()
{
$('#formlogin').empty().html('<img src="loading.gif" />');
$.post('authenticate.php',
        {

        }, function(data)
        {
   $('#formlogin').empty().html(data);
        });
        return false;
});

});
</script>
</head>
<body>
<form id='formlogin'>
<input type='text' name='username' id='username' />
<input name='pass' id='pass' type='password' />
<input type='submit' value='login' name="sub" id="sub" />
</form>
</body>
</html>

Friday 1 October 2010

Send a file attachment and send as an e-mail in PHP

This is not the full story. First you need a form to collect the data and put it in a field (in this case) called myValue.

This piece of code takes the field contents, creates a text file and sends it.


<?php
    $filetitle = "testFile.txt";  
    $data = $_POST["myValue"]);
    $to = 'jimmy@googlemail.com';
    $subject = 'My subject';  
    $filetype = "text/plain";  
    $email_from = "jammy@googlemail.com";  
    $headers = "From: ".$email_from;      
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";
  
    $email_message .= "This is a multi-part message in MIME format.\n\n" .
    "--{$mime_boundary}\n" .
    "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .
    $email_message . "\n\n";
  
    $data = chunk_split(base64_encode($data));
  
    $email_message .= "--{$mime_boundary}\n" .
    "Content-Type: {$filetype};\n" .
    " name=\"{$filetitle}\"\n" .  
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "--{$mime_boundary}--\n";
  
    $ok = @mail($to, $subject, $email_message, $headers);

    if($ok)
    {
        echo "It worked";
    }
    else
    {
        die("It failed");
    }
?>

Send Form information to PHP through jQuery

"Why would I do this?", I hear you ask. The answer is simple, by sending information through jQuery you open yourself up to losing browser refresh and a better UI. There are 2 files in this example:
The HTML file, which also contains the jQuery.
The PHP file which would do the processing.

See demo.

Let's start with the HTML file.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery and PHP Form</title>
<style type="text/css">
html, body
{
 font-family:sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
    $('#sendTheData').click(function()
    {
        $.post("sendThedata.php",
        {
            myValue:$('#lname').val()
        }, function(data)
        {
    alert(data);
        });
        return false;
    });
});
</script>
</head>
<body>
<form>
  <input type="text" name="lname" id="lname" /><br />
  <input type="submit" value="Submit" id="sendTheData" />
</form>
</body>
</html>


Now for the PHP file:

<?php
  echo 'Got '.$_POST['myValue'];
?>

Friday 17 September 2010

How to create an e-mailable PDF form in OpenOffice.org

Suppose you wanted to send someone a PDF with form elements and a submit button at the bottom. Suppose when they clicked on the button you wanted the form contents to be sent as a PDF back to you. Here is how to do it.
Stage 1
Create the form in OpenOffice.org
Step 1
Create a new document using OpenOffice.org writer.
Step 2
Load the form controls using View->Toolbars->Form Controls and View->Toolbars->Form Design.
Step 3
Get your document ready for form elements by adding a title and pressing Carriage Return (Enter, <CR>, Return) a few times.
Step 4
Put the document in design mode using the 'Design Mode On/Off' switch in the form controls.
Step 5
Add form items to your document by selecting them from the form controls dialog, then dragging on to your page.
Step 6
Your final form entry should be a submit button. In the button properties, the 'Action' field should be set to 'Submit form'.
Stage 2
Set the form to e-mail
Step 1
Click on the 'Form' (properties) button on the form controls dialogue.
Step 2
Set the URL field to mailto:your.emailaddress@yourdomain
Stage 3
Export your document to PDF making sure that the 'Submit format' is FDF.
Stage 4
Test your newly exported PDF by filling in the fields and pressing the submit button.

Friday 27 August 2010

Form validation using jQuery

The code below offers a simple example, which you can build upon, of using jQuery to validate your forms. I have added a few comments in green to explain what is going on.

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validate form</title>
<!-- Get jQuery from Google -->
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<!-- Get the validation library from Microsoft -->
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
/* apply validation rules to myform */
$("#myform").validate(
{
rules:
{
/* apply a simple rule to contactname */
contactname: "required",
/* apply more rules to email */
email:
{
required: true,
email: true
}
},
/* provide special messages to contactname */
messages:
{
contactname: "Please enter a contact name"
}
});
});
</script>
<style type="text/css">
body
{
font-family:sans-serif;
}
</style>
</head>
<body>
<form method="post" action="" id="myform">
<label for="name">Name:</label>
<!-- Adding the class "required" works makes coincides with the jQuery call for this field -->
<input type="text" size="20" name="contactname" id="contactname" value="" class="required" /><br />
<label for="email">Email:</label>
<!-- Adding the class "required email" works makes coincides with the jQuery call for this field -->
<input type="text" size="20" name="email" id="email" value="" class="required email" /><br />
<label for="message">Message:</label>
<!-- No validation required for the message -->
<textarea rows="5" cols="20" name="message" id="message"></textarea><br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>