Chapter 3. Form Tools

Ask yourself a question: do you like filling in forms? If, as I suspect, the answer is no, then join the masses—there is nothing worse than filling in a form online, only to find you've entered in something incorrectly, and you have to go back and change it…

Enter jQuery Tools' Form Tools!

This group of 3 useful tools may not be as popular as some of the other tools in the library, but they still serve a useful function.

In this chapter we will learn about the following:

  • How to use Validator to ensure a form is correctly filled out, or to display errors when this is not the case
  • How to update the basic style of DateInput, using elements of jQuery UI's themes
  • How to turn RangeInput into a browser, so you can scroll through a number of products, and some tips on how to combine it with other tools

So…what are you waiting for? Let's get started with looking at Validator.

Using Validator

Validators can be used to ensure whether a form is correctly filled out. Validators can also be used to display the errors.

Why basic Validator?

The art of form filling, as defined by Wikipedia, means that you cannot simply submit forms with any old rubbish, or saying "put rubbish in, and you get rubbish out" will definitely be true. It is crucial to ensure that the content you enter at least conforms to some form of minimum standard—one of the tools that can help with this is Validator. Let's have a look at this component of the Tools library in a little more detail.

Note

Data validation is the process of ensuring that a program operates on clean, correct and useful data.

Usage

The basic code for Validator is in two parts—the first part is the HTML structure, with the second part a single line call to the Validator tool:

<form id="myform" novalidate="novalidate">
<fieldset>
<h3>Sample registration form</h3>
<p> Enter bad values and then press the submit button. </p>
<p>
<label>email *</label>
<input type="email" name="email" required="required" />
</p>
<p>
<label>website *</label>
<input type="url" name="url" required="required" />
</p>
<p>
<label>name *</label>
<input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" />
</p>
<p>
<label>age</label>
<input type="number" name="age" size="4" min="5" max="50" />
</p>
<p id="terms">
<label>I accept the terms</label>
<input type="checkbox" required="required" />
</p>
<button type="submit">Submit form</button>
<button type="reset">Reset</button>
</fieldset>
</form>

Once you have the form set up, then you need to add the call for Validator here's the basic code:

$("#myform").validator();

Note

Notice that this includes the novalidate attribute on the form—this is to force IE not to try to use the HTML5 validator that works in more modern browsers, but to use that from jQuery Tools instead.

With this in mind, let's put it into practice, by setting up a demonstration of how we can use Validator in a form.

Project: improving styling, and adding custom field validators

We're going to use an existing form, available from the jQuery Tools site, and add some tweaks in the form of additional validators, and changes to the configuration.

Creating the basic HTML structure

Open up the text editor of your choice, and copy in the following code—you will notice that it follows a similar pattern to most of the projects in this book:

<!DOCTYPE html>
<html>
<head>
<title>jQuery Tools standalone demo</title>
<!-- include the Tools -->
<script src="http://cdn.jquerytools.org /1.2.6/full/jquery.tools.min.js"></script>
</head>
<body>
</body>
</html>

Adding in the form details

Okay. Now we have the basic structure in place, let's start filling it out with a little detail. First up is the form content, with the fields that we are going to validate—so copy in the code below in between the<body> tags:

<form id="myform">
<fieldset>
<h3>Sample registration form</h3>
<span class="errorlabel">Oops - it seems there are some errors! Please check and correct them.</span>
<p> Enter bad values and then press the submit button. </p>
<p>
<label>email *</label>
<input type="email" name="email" id="email" required="required" />
</p>
<p>
<label>website *</label>
<input type="url" name="url" required="required" />
</p>
<p>
<label>name *</label>
<input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" />
</p>
<p>
<label>time *</label>
<input type="time" name="time" required="required" data- message="Please enter a valid time"/>
</p>
<p>
<label>age</label>
<input type="number" name="age" size="4" min="5" max="50" />
</p>
<p>
<label>password</label>
<input type="password" name="password" minlength="4" />
</p>
<p>
<label>password check</label>
<input type="password" name="check" data-equals="password" />
</p>
<p>
<label>filename *</label>
<input type="file" name="uploadfile" required="required" />
</p>
<p>
<input type="phone" name="phone" data-message="Please enter a valid US telephone number." required="required" pattern="(?:1-?)?(d{3})[-.]?(d{3})[-.]?(d{4})" />
</p>
<p>
<label>Gender</label>
<select value="" required="required" name="sex">
<option></option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</p>
<p id="terms">
<label>I accept the terms</label>
<input type="checkbox" required="required" />
</p>
<button type="submit">Submit form</button>
<button type="reset" id="clearform">Reset</button>
</fieldset>
</form>

Note

Notice that there are a number of additional parameters that pop up in the code, such as the pattern attribute in the Telephone input field. These are used by Validator and/or its additional custom validators, as a basis for validating text entered by the person visiting the site.

Styling the form

Now that is done, we need to add in the all important styling—note that this does include some additional styles for the purposes of this demo, but are not necessarily required in your live projects:

<style>
/* body, a:active and : focus only needed for demo; these can be removed for production use */
body { padding: 50px 80px; }
a:active { outline: none; }
:focus { -moz-outline-style: none; }
/* form style */
#myform { background: #333 0 0; padding: 15px 20px; color:
#eee; width: 440px; margin: 0 auto; position: relative;
-moz-border-radius: 5px; -webkit-border-radius: 5px; border- radius: 5px; }
/* nested fieldset */
#myform fieldset { border: 0; margin: 0; padding: 0;
background: #333 url(logo-medium.png) no-repeat scroll
215px 40px; }
/* typography */
#myform h3 { color: #eee; margin-top: 0px; }
#myform p { font-size: 11px; }
/* input field */
#myform input { border: 1px solid #444; background-
color: #666; padding: 5px; color: #ddd; font-size: 12px;
text-shadow: 1px 1px 1px #000; -moz-border-radius: 4px;
-webkit-border-radius: 4px; border-radius: 4px; }
/* take care here: support for :focus and :active limited in some browsers!
#myform input:focus { color: #fff; background-color: #777; }
#myform input:active { background-color: #888; }
/* button */
#myform button { outline: 0; border: 1px solid #666; }
/* error message */
.error { font-size: 11px; color: #f00; display: none; }
.error p { margin:15px; margin-left: 20px; font-weight: bold; background-color: #fff; -moz-border-radius:4px;
-webkit-border-radius: 4px; padding: 2px; border-radius: 4px;}
/* field label */
label { display:block; font-size:11px; color:#ccc; }
#terms label { float: left; }
#terms input { margin: 0 5px; }
.invalid { -moz-box-shadow: 0 0 2px 2px #f00; -webkit-box-shadow: 0 0 2px 2px #f00; box-shadow: 0 0 2px 2px #f00; }
.errorlabel { display: none; font-size: 14px; font-weight: bold; color: #f00; }
.error img { position: absolute; margin: 15px 15px 15px 0;}
.errorhilite { border: 3px solid #f00; }
</style>
</head>

The final part—the script

The final part required is the all important script, to make it all work—as this is a reasonably long script, we will break it down into sections, starting with the validators.

Custom Validators

While Validator will use standard HTML4 and HTML5 validators, the functionality only really comes into its own when you add in custom validators, that are not available as a part of the normal library. We have five examples of custom validators in this demo, so copy the following code into your site—this should be the last stage on your page, or in the<head> area, as long as the document.ready() function is used accordingly:

<script>

This validator performs a check on<select> drop downs:

// custom Validator for <select> dropdowns
$.tools.validator.fn("select", "Select a value", function(input, value) {
return (value == 'none') ? false : true;
});

If you want to use radio buttons, then this is the validator code you need to use:

// custom Validator for radio buttons
$.tools.validator.fn("[group-required]", "At least one option needs to be selected.", function(input) {
var name = input.attr("group-required");
var group_members = $('input[name=' + name + ']'),
var checked_count = group_members.filter(':checked').length;
if((checked_count == 0) && (group_members.first().attr('id') == input.attr('id'))) {
$('input[name=' + name + ']').click(function() {
validate_form.data("validator").reset($('input[name=' + name + ']'));
});
return false;
} else {
return true;
}
});

The validator below will do a pattern match for a valid time:

// custom Validator for "time" input type
$.tools.validator.fn("[type=time]", function(el, value) {
return /^(2[0-4]|[01]?d):[0-6]d$/.test(value) ? true : "Please provide a valid time, using military format";
});

This validator will flag an error if the minimum character length is not obeyed:

// custom alidator based on minimum required length
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
if (isNaN(min)) {
return true; // not a valid minlength, so skip validation
} else {
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
fi: "Kentän minimipituus on " +min+ " merkkiä"
};
}
});

This validator will show an error if the uploaded file type is not one of the pre-determined types:

// custom validator based on a required filetype
$.tools.validator.fn("[type=file]", "Please choose a file with an allowed extensions", function(input, value) {
if ($(":file").val() != "") {
return /.jpgpnggifpdfdoc	xt)$/.test(value);
} else {
return true;
}
});

The real heart of the validator script is as given below, it contains the call to jQuery Tools' Validator functionality, with a number of additional configuration options. In order, they do the following:

  • position: It controls the location on screen where the text will appear
  • speed: It determines how fast or slow the error message appears
  • offset: It is used in conjunction with position to fine-tune the location on screen
  • errorClass and errorInputEvent: The CSS style to use on the error message, and the trigger for the input validity check
  • message: The text of the error message, including any images (as shown here)
  • inputEvent: It revalidates text each time the user "blurs" or moves away from the element—this is used particularly on the checking of<select> tags

Copy this into your script section:

$(document).ready(function () {
$("#myform").validator({
position: 'center right',
speed: 'slow',
offset: [0, 10],
errorClass: 'invalid',
errorInputEvent: 'keyup change',
message: '<div><img src=images/exclamation.png></div>',
inputEvent: "blur"
});
})

This next section performs two functions—the first one is to set Validator to automatically reposition the error message text, if the window is resized; the second one adds a red border on fields that do not validate properly, on a trigger of "onFail", when the submit button is pressed:

// get handle to the Validator API
var myForm = $("#myform"), api = myForm.data("validator");
api.reflow();
myForm.bind("onFail", function(e, errors) {
// we are only doing stuff when the form is submitted
if (e.originalEvent.type == 'submit') {
$(".errorlabel").css({ display: 'block'});
// loop through Error objects and add the border color
$.each(errors, function() {
var input = this.input;
input.css( 'errorhilite' ).focus(function() {
input.css( 'errorhilite' );
});
});
}
});

The final part of this script is a reset function that clears the red border set against any field that doesn't validate correctly:

$("#clearform").click(function() {
myForm.reset();
$(".errorlabel").css({ display: 'none' });
// loop through Error objects and add the border color
$("input, select").each(function(index) {
$(this).css({ border: '' });
});
});
})
</script>

If all has worked correctly, then you should see something like the form shown in the next screenshot:

Custom Validators

"It seems very negative, this onFail…"

Yes, it is true—a potential downside of Validator is that it does feel very one-sided in that it concentrates on only when input entries fail. However, it is possible to include code to display a confirmation or message if the validator deems that the entry concerned does match the required pattern.

Note

You should note that,this is a concept only at the moment; it is meant as a starting point for your own development, and would need thorough testing before putting into production use.

To do this, you can try the following:

  1. Add the following into your style sheet:
    input.valid {
    background-image: url(images/accept.png);
    background-position: right top;
    background-repeat: no-repeat;
    }
    input.valid.invalid {
    background-image: none;
    }
    
  2. Add this to your JavaScript call to jQuery:
    // use API to assign an event listener
    api.onSuccess(function(e, els) {
    $("input[required]").addClass('valid'),
    // we don't want to submit the form. just show events.
    return false;
    });
    
  3. Add this to the bottom of your reset method:
    $('input').removeClass("valid");
    
  4. Add this line to the configuration set up for Validator:
    errorInputEvent: 'keyup change',
    

The code is not perfect—it has some bugs in it, so should only be treated as a starting point for your own ideas. If you do implement the code above, then you should see something like the following screenshot:

"It seems very negative, this onFail…"

Validator—a final thought

This demo scratches just the surface of what can be done with Validator—Validator will happily work with jQuery Tools' Overlay functionality, so that you could show the errors in a dialog box, with the overlay mask behind, for example. You can even use jQuery UI to provide that dialog box effect as well—the key to using jQuery UI is to declare the call to jQuery Tools first, then reassign the Tabs object in Tools to use a different naming convention, otherwise it will conflict with UI.

In the next section, we will take a look at another important tool in the library—DateInput.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset