Articles in the ‘Features’ Category

JxLib: An Introduction

Written By Aaron Newton, on Monday, December 26th 2011, 3:02pm

Jon Bomgardner is a contributor to the jxlib.org project. After recently joining the MooTools Developer mailing list and sharing his experience in upgrading jxlib to MooTools 1.4.2 we asked him to share his work here on the blog.

What is JxLib

JxLib is a JavaScript UI framework built on MooTools. It allows web developers and designers to quickly build user interfaces for their applications. JxLib is based on some sweet HMTL markup and strives to be fully CSS compliant. It is also a modular library allowing you to pick and choose from the available components as well as giving you the ability to override default behaviors and extend core classes.

All of this flexibility is, in large part, due to being built on MooTools. The library is heavily object-oriented with a huge number of classes inheriting from a single base. If you know how to use the MooTools class system you will quickly get up to speed on JxLib. In addition to being based on HTML and CSS, which provides an amazing amount of flexibility itself, the library’s architecture is based on a plugin system that allows additional functionality to be added to each component at the developer’s discretion.

A couple of quick examples

So, I wanted to show a couple of easy examples of what you can do with JxLib. There’s a ton of functionality built in and for more complete examples you can check out the examples page at jxlib.org. Here are 3 quick jsfiddles that you can play around with to get a feel of some of the functionality.

Example 1: Drop Down Menu Toolbar

This example shows a simple menu toolbar with cascading menus

Example 2 : Jx.Form and Form fields

This example shows off Jx.Form and a lot of the bundled fields you get out of the box.

Example 3: The New Jx.Container and Jx.LayoutManager classes

This one shows off some of the new work in JxLib 3.1.1. It creates the entire layout using a single javascript object. Check out the center panel’s tabs for a look at Jx.Editor and other components.

Experiences achieving compatibility with Core 1.4.2

I am happy to report that the conversion to Core 1.4.2 went relatively easily. The biggest conversion headache was when I originally worked on getting compatibility with 1.3.2 - that was a ton of work. We used many of the $ global methods ($defined, $H, $A were some of the big ones) and they were littered about the code base quite liberally. I really didn’t want to use the compatibility layer that the folks here at MooTools so graciously provided everyone because the download was big enough as it was. Hunting down all of those changes took the most time. In the process of doing so however I learned a few interesting tidbits:

First, it was best to replace $defined() with a check for undefined and null. for example:

if ($defined(some_variable)) {

became

if (some_variable !== undefined && some_variable !== null) {

I realize that the conversion docs state that checking undefined should be enough but when I tried that at first I got a LOT of weird errors. This change fixed them.

The other thing I discovered is that Object.each and Object.keys weren’t all that useful when the object you’re using them with was actually on the prototype of the class they were in. For example, in JxLib 2.0 we had this code:

processElements: function(template, classes) { 
    var keys = classes.getValues(); 
    elements = this.processTemplate(template, keys); 
    classes.each(function(value, key) { 
        if (key != 'elements' && elements.get(value)) { 
            this[key] = elements.get(value); 
        } 
    }, this); 
    return elements; 
}

It seems that those two functions use hasOwnProperty() which was causing the loop above to have 0 iterations because the classes variable was actually this.classes which was found on the prototype of the class. When converting to Core 1.3.2 (and subsequently 1.4.2) we had to use this:

processElements: function(template, classes) { 
    var keys = [], 
        values = []; 
    for (var key in classes){ 
        if (key !== undefined) { 
            values.push(classes[key]); 
            keys.push(key); 
        } 
    } 
    elements = this.processTemplate(template, values); 
    keys.each(function(key){ 
        if (key != 'elements' && elements[classes[key]] !== undefined && elements[classes[key]] !== null) { 
            this[key] =  elements[classes[key]]; 
        } 
    },this); 
    return elements; 
}

Once those were figured out, and we had full compatibility with 1.3.2, moving up to 1.4.x was pretty painless. For more info on what I learned during the conversion (some of it not MooTools or even javascript related) check out my blog post.

Get More information

You can get more information on JxLib at the following places:

If you have any questions or comments feel free to leave those below or in the Google group (linked above). Also, if you like what you’ve seen and read here please consider pitching in and helping to make JxLib even better. We have many plans for future releases but could always use a few extra hands.

More than Meets the Eye: Form Validator

Written By Aaron Newton, on Friday, April 30th 2010, 3:09pm

Continuing with my “More than Meets the Eye” series, today I want to talk to you about the MooTools More Form.Validator. There was a comment left on my last post in this series (about Form.Request) specifically requesting that I cover this relatively complex plugin that’s useful for telling users about the validity of data they enter into forms before they send them.

Getting Started with Validators

The main class you need to concern yourself with is the Form.Valdiator class itself which provides methods that apply specific rules to inputs to see if they are valid. You can then choose how you want to inform your users that they need to address these problems, but that’s not the job to Form.Validator (though it is the job of Form.Validator.Inline, which we’ll cover in a bit).

Let’s talk little bit about the rules that are applied. Form.Validator allows you to define rules that test the state of an input and return true or false - true if the input passes the validation rule, and false if it doesn’t. Here’s a simple example:

Form.Validator.add('doesNotContainTheLetterQ', {
        errorMsg: 'This field cannot contain the letter Q!',
        test: function(field){
                return !field.get('value').test(/q/,'i');
        }
});

The above code adds a global validator that allows you to assert that the input doesn’t use the letter Q. The arguments are the validators’ key and then an object that contains an error message to show the user should they encounter the error, and a function that is passed the input as an argument. This function inspects the value or, really, anything you like, and then returns true or false.

The key you give your validator is important. At any time you can validate a field against any validator by using this key as a reference by doing:

myFormValidator.test(key, input[, warnOnly]);

The first two arguments are the important ones here; the key of your validator and the input to test. Where things get interesting are when Form.Validator does this for you. By giving your input that key as a css class name, you tell Form.Validator to validate that field with this validator. In this manner you can quickly and unobtrusively decorate your inputs with the requirements and validate the form. If something goes wrong with your JavaScript, your form will submit as normal. Here’s a really simple example:

The alerts aren’t pretty, but you can see how our validator is now applied when you submit the form.

Form.Validator ships with several validators listed in the documentation. These include simple stuff like required that just validates that the user put something - anything - in the input. But there are also validators for email addresses, only letters, dates, urls, etc. The key is you can write your own - you don’t need to wait for us to release something for you to make use of it. There are an extended list of validators in Form.Validator.Extras that include some edge cases. Things like validating that two inputs have the same value (like an email verification for example).

Using Validators with Arguments

It’s also possible to configure validators with data unique to the input. For example, let’s say you want to have an input with a minimum length validator - the user must type in at least 5 characters. You could write a validator called minimum5 or whatever, but then you’d have to duplicate it for any other character length. For this purpose, Form.Validator allows you to assign values to the input, like so:

<input type="text" name="username" class="minLength:10" id="username"/>

These values - the 10 and 100 values in the example above - get passed along as JSON decoded values to the validator. Here’s what that looks like:

Form.Validator.add('minLength', {
    errorMsg: function(element, props){
        return 'Please enter at least {minLength} characters (you entered {length} characters).'.substitute({minLength:props.minLength,length:element.get('value').length });
    },
    test: function(element, props){
        if (props.minLength != null) return (element.get('value').length >= props.minLength;
        else return true;
    }
});

As you can see, the error message (which in our previous validator was just a string - the message) can also be a function which is passed the input and then any properties defined in the HTML. The fact that the message can be a function allows you to include information not only about how the validator is configured but also other information, like some aspect of the value the user actually entered. The test is also passed along these p roperties of course which allows you to make the properties a condition of the test. We could, in theory, rewrite our doesNotContainTheLetterQ validator to accept an argument about the character (or, better yet, characters) that we want to disallow:

Form.Validator.add('doesNotContain', {
    errorMsg: function(field, props){
        return 'The value you input cannot contain any of the following letters: ' + props.doesNotContain;
    },
    test: function(field, props){
        if (props.doesNotContain)
            return !field.get('value').match(new RegExp('[' + props.doesNotContain + ']', 'i'));
        else return true;
    }
});

Note that the properties defined have to be JSON decodable, so you can’t have your input like this:

<input type="text" class="doesNotContain:qz"/>

Instead you’d have to quote the string:

<input type="text" class="doesNotContain:'qz'"/>

Here’s our example:

The base Form.Validator class comes with a plethora of options and events. You can configure it to validate inputs whenever they change (on blur), or to only show one error at a time (serial). You can tell it to ignore hidden fields (those that are not visible, there’s no point in validating inputs with type=”hidden”) and disabled inputs. There are numerous useful methods that let you run the entire validation routine on the form (.validate()), reset all the errors (.reset()) or validate / reset a specific field (.validateField() and .resetField()). You can pause the validator and resume it (.stop() and .start()) as well as ignore / un-ignore a specific field (.ignoreField() and .enforceField()) and more. There’s even an element method that lets you validate a form (Element.prototype.validate).

Form.Validator.Inline - the “Pretty” One

Now that we’ve covered the basics of how Form.Validator works, let’s consider the fact that our examples so far have been rather ugly (who wants alert messages?). MooTools More ships with a default implementation that smoothly displays messages inline, right after the input: Form.Validator.Inline. This class is the “pretty” version of Form.Validator but don’t think of it as the only game in town. You can easily implement your own “pretty” version without a lot of effort. If you want to put errors in a popup or fade them in over the entire screen or play a sound it doesn’t matter. The base Form.Validator class is there for you.

Looking at the Form.Validator.Inline implementation, you’ll find all the same options and methods from Form.Validator along with a few extras that control how your messages appear. For instance, by default, the validation rules show up immediately after the input. This requires a bit of forethought in how you structure your HTML. If your input is inline with something else (like a submit button), validation errors are going to change that when they appear (because they are divs, which by default are block level elements).

The only real option that Form.Validator.Inline has to offer is whether or not to scroll to errors (useful if your form is long and will likely cause the user to scroll to the submit button). Here’s a simple example, building on our previous one:

As you can see, the error message slides in, but it breaks our layout a bit. Let’s do some CSS work to make this look a little nicer.

It’s not The Sistine Chapel but it does look nicer. Our error doesn’t appear to break our layout anymore either.

As a final example, I’ll show you a version that extends Form.Validator.Inline to put the validation messages in tips that popup pointing at the input. Here’s a demo:

If you want you can check out the source on github and download it with its dependencies on Clientcide.

Go Forth and Validate

Overall the purpose of Form.Validator is not to be the only solution for displaying validation messages to your users, but rather a flexible solution for client side form validation on which to build. You can extend it and manipulate it to display messages in any way you choose - and you should!. The default “pretty” implementation - Form.Validator.Inline - is just one way to use the class. In my opinion Form.Validator is one of the classes in MooTools More that shows off the power of MooTools’ object oriented design, allowing for a great deal of flexibility and reuse.

Thanks to Lloyd for suggesting this edition’s topic. If there’s a plugin in MooTools More you’d like me to focus on next time, by all means, make a suggestion in the comments.

Aaron Newton is a contributor to MooTools and the principal developer of MooTools More. He is the author of the book MooTools Essentials as well as the Mootorial online MooTools tutorial. He posts (rarely these days) at his blog Clientcide.com and (much more often) on Twitter as anutron. He works for Cloudera, (which is hiring, by the way).

What’s New in 1.2: Swiff

Written By Michelle Steigerwalt, on Tuesday, February 12th 2008, 3:17pm

Today we’re going to talk about Swiff, which lets you combine Flash and JavaScript to do things MooTools can’t do on its own.

(more…)

What’s New in 1.2: Element Storage

Written By Tom Occhino, on Tuesday, January 22nd 2008, 6:13pm

Another new feature that’s been built into the latest version of MooTools is the Element Storage. This article describes the usage of this great new feature, as well as why it was developed, and how it can be used to keep your applications organized and efficient.

(more…)

MooTools Foundations: Natives and Elements

Written By Tom Occhino, on Wednesday, October 31st 2007, 8:00am

We haven’t had this blog for very long, and talking to many users recently, I became aware of the fact that many people just don’t understand how powerful MooTools actually is. The purpose of this series of articles is to shed a little light on some of the functionality provided by MooTools that many users might be missing. I think maybe it’s time we got everyone caught up to speed. First topic… Natives and Elements!

(more…)