Jquery Course

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 HTML5 tag can be used to embed an external application (SWF, PDF) in web page?
<mark> <embed> <canvas>
<embed src="flash_game.swf" width="450" height="350" />
Which CSS pseudo-element adds a special style to the first line of a text?
:first-letter :before :first-line
#id:first-line {
  font-weight: bold;
  color: blue;
}
Click on the window object property which gets or sets the URL of current page.
window.location window.self window.status
var url = window.location;
alert(url);
Indicate the PHP function used to get the contents of a file or page and store it into a string.
fopen() file_put_contents() file_get_contents()
$homepage = file_get_contents("http://coursesweb.net/");
echo $homepage;
Validate and Submit Form

Last accessed pages

  1. Output or Force Download MP3 with PHP (5825)
  2. Snap to Objects and Snap Align (2880)
  3. Highlight Images on click (6765)
  4. innerHTML and outerHTML to Get and Replace HTML content (30639)
  5. PHP Unzipper - Extract Zip, Rar Archives (32334)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (352)
  2. CSS cursor property - Custom Cursors (41)
  3. The Mastery of Love (39)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (34)
  5. Read Excel file data in PHP - PhpExcelReader (31)