Validate Form

Before submit a form to a server script, it is indicated to perform some minimal validations on the client side, like the number of characters in a field and the correct form of an e-mail address.


In the next example we use jQuery to validate the following form (two text input fields, two radio buttons, a select list, and a textarea).
<form action="script.php" method="post">
 Name: <input type="text" name="name" id="name" /><br />
 E-mail: <input type="text" name="email" id="email" /><br />
 <span id="gen">
  Gender: <input type="radio" name="gen" value="man" />Man
  <input type="radio" name="gen" value="woman" />Woman
 </span><br />
 Age, between: <select name="age" id="age">
  <option>..select..</option>
  <option value="5-10">5-10</option>
  <option value="11-18">11-18</option>
  <option value="19-30">19-30</option>
  <option value="31-50">31-50</option>
  <option value="51-70">51-70</option>
  <option value="71+">71+</option>
 </select><br />
 Message:<br />
 <textarea name="msg" id="msg" rows="4" cols="33"></textarea><br />
 <input type="submit" name="submit" value="Submit" />
</form>

Now we write a jQuery code that detects when the user attempts to submit the form. We check if the "name" field has at least two characters, if the e-mail address has the correct form, if a radio button is checked and a select options is selected, and if the textarea has at least 5 characters.
If all the form elements are correctly filled, submits the form, else, adds a CSS class="error" to the invalid elements, and returns an Alert with a message.
The "error" class is defined in a CSS style to add a red border.
- Below there is a demo with this form.
This is the jQuery code to validate the form above:
<style type="text/css"><!--
.error { border:2px solid red; }
--></style>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // when a form is submited, get its data and validate the fields
  $('form').submit(function() {
    // gets field values
    var name = $(this).find('input[name="name"]');          // Name
    var email = $(this).find('input[name="email"]');        // E-mail
    var gen = $(this).find(':radio:checked');                         // Gender
    var age = $(this).find('select[name="age"]');           // Age
    var msg = $(this).find('#msg');                                   // Message

    // remove class "error" from al elements
    // sets a variable "error" used to deermine if submit or no the form
    $('*').removeClass('error');
    var error = 0;
    var regx = /^([a-z0-9_\-\.])+\@([a-z0-9_\-\.])+\.([a-z]{2,4})$/i;   // regexp for e-mail

          /* Validate the fields (adds class "error" to invalid fields and set error=1) */
    // check "name"
    if(name.val().length<2){
      name.addClass('error');
      error = 1;
    }
    // check "email"
    if(!regx.test(email.val())){
      email.addClass('error');
      error = 1;
    }
    // check radio input "gen", if undefined (not checked),
    // add class "error" to element that includes radio inputs
    if(gen.val()==undefined){
      $('#gen').addClass('error');
      error = 1;
    }
    // check "age", if no selected (value of <select> is the value of first <option>, initially displayed)
    if(age.val()==age.find('option:first').val()){
      age.addClass('error');
      error = 1;
    }
    // check "msg"
    if(msg.val().length<5){
      msg.addClass('error');
      error = 1;
    }

    // if error is 0, submit the form
    // else alerts a message and blocks the submission by returning false
    if(error==0) {
      $(tihs).submit();
    }
    else {
      alert('Please fill all fields with red border');
      return false;      // necesary to not submit the form
    }
  });
});
--></script>

- The val() function returns the value of a form field.
- $(this).find('input[name="name"]') - returns the input element with name="name" in the current object.
- $(this).find(':radio:checked') - returns the checked radio item(s) in the current object.
- $(this).find('select[name="age"]') - returns the <select> element with name="age" in the current object.
- $(this).find('#msg') - gets the element with id="msg" in the current object.

Submit the form via Ajax

To submit form data via Ajax to a server script, you must add the "name=value" pairs of the form fields in a string, separated by "&". This can be easily accomplished with jQuery serialize() method.
The serialize() method encodes a set of form elements as a string for submission.
After we validate the form, if there is no errors, we can apply this method and submit form data.

Hesre's a complete example. Validate the form created above and submit it with jQuery ajax to a PHP script ("script.php" file), then include the response of the script into a <div> on the page (For details, see the comments in code).
- The response from PHP contains a HTML code with form data submited.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Validate Submit</title>
<style type="text/css"><!--
.error { border:2px solid red; }
--></style>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
  // when a form is submited, get its data and validate the fields
  $('form').submit(function() {
    // gets field values
    var name = $(this).find('input[name="name"]');          // Name
    var email = $(this).find('input[name="email"]');        // E-mail
    var gen = $(this).find(':radio:checked');               // Gender
    var age = $(this).find('select[name="age"]');           // Age
    var msg = $(this).find('#msg');                         // Message

    // remove class "error" from al elements
    // sets a variable "error" used to submit or no the form
    $('*').removeClass('error');
    var error = 0;
    var regx = /^([a-z0-9_\-\.])+\@([a-z0-9_\-\.])+\.([a-z]{2,4})$/i;   // regexp for e-mail

          /* Validate the fields (adds class "error" to invalid fields and set error=1) */
    // check "name"
    if(name.val().length<2){
      name.addClass('error');
      error = 1;
    }
    // check "email"
    if(!regx.test(email.val())){
      email.addClass('error');
      error = 1;
    }
    // check radio input "gen", if undefined (not checked),
    // add class "error" to element that includes radio inputs
    if(gen.val()==undefined){
      $('#gen').addClass('error');
      error = 1;
    }
    // check "age", if no selected (value of <select> is the value of first <option>, initially displayed)
    if(age.val()==age.find('option:first').val()){
      age.addClass('error');
      error = 1;
    }
    // check "msg"
    if(msg.val().length<5){
      msg.addClass('error');
      error = 1;
    }

    // if error is 0, serialize form data and send the data string to server
    // else alert a message
    if(error==0) {
      var srl = $(this).serialize();

      $.ajax({
        type: 'post',
        url: 'script.php',
        data: srl,
        beforeSend: function() {
          // before send the request, displays a "Loading..." messaj in the element where the response will be placed
          $('#resp').html('Loading...');
        },
        timeout: 10000,        // sets timeout for the request (10 seconds)
        error: function(xhr, status, error) { alert('Error: '+ xhr.status+ ' - '+ error); },     // alert a message in case of error
        success: function(response) {
          $('#resp').html(response);
        }
      });
    }
    else { alert('Please fill all fields with red border'); }

    return false;      // necesary to not open the page when form is submited
  });
});
--></script>
</head>
<body>
<div id="resp">Here will be displayed the response from server.</div>
<h4>Fill the form and submit data</h4>
<form action="script.php" method="post">
 Name: <input type="text" name="name" id="name" /><br />
 E-mail: <input type="text" name="email" id="email" /><br />
 <span id="gen">
  Gender: <input type="radio" name="gen" value="man" />Man
  <input type="radio" name="gen" value="woman" />Woman
 </span><br />
 Age, between: <select name="age" id="age">
  <option>..select..</option>
  <option value="5-10">5-10</option>
  <option value="11-18">11-18</option>
  <option value="19-30">19-30</option>
  <option value="31-50">31-50</option>
  <option value="51-70">51-70</option>
  <option value="71+">71+</option>
 </select><br />
 Message:<br />
 <textarea name="msg" id="msg" rows="4" cols="33"></textarea><br />
 <input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Demo:
Here will be displayed the response from server.

Name:
E-mail:
Gender: Man Woman
Age, between:
Message:

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <img> tag for the address of the image?
href src rel
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;
#id {
  display: none;
}
What instruction stops the execution of a while() or for() statement?
continue prompt() break
for(var i = 0; i< 8; i++) {
  if(i > 1) break;
  alert(i);
}
Indicate the function that can create a constant.
define() include() defined()
define("CONSTANT_NAME", "value");
echo CONSTANT_NAME;
Validate and Submit Form

Last accessed pages

  1. PHP Simple HTML DOM Parser (690)
  2. CSS Border (738)
  3. Add, Change, and Remove Attributes with jQuery (3626)
  4. Script Users Register, Login, Online (2484)
  5. Bubble Tanks 3 (1732)

Top accessed pages

  1. PHP-MySQL free course, online tutorials PHP MySQL code (5222)
  2. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (4995)
  3. Get Attribute (ID, Class, Name, Title, Src) with jQuery (4785)
  4. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (4628)
  5. PHP Chat Script (4369)