Fork me on GitHub

Happy.js

Lightweight form validation for jQuery or Zepto.js

Download

zip tar

Or... you can clone the whole project from GitHub with Git by running:

$ git clone git://github.com/henrikjoreteg/Happy.js

$('form').isHappy()? The Quick Demo:

Step 1. - Define your form

<form id="awesomeForm" action="/lights/camera" method="post">
  <input id="yourName" type="text" name="name" />
  <input id="email" type="text" name="email" />
</form>

Step 2. - Define your validation scheme

$('#awesomeForm').isHappy({
    fields: {
      // reference the field you're talking about, probably by `id`
      // but you could certainly do $('[name=name]') as well.
      '#yourName': {
        required: true,
        message: 'Might we inquire your name'
      },
      '#email': {
        required: true,
        message: 'How are we to reach you sans email??',
        test: happy.email // this can be *any* function that returns true or false
      }
    }
  });

Step 3. - There is no step 3!

That's it. Happy.js will now validate individual fields on blur events and all fields on submit. If validation fails two things happen:

  1. The field will get an unhappy class (yes, I'm quite serious).
  2. The field will get a <span> right before it, in the DOM with a class of unhappyMessage and an id of whatever the field's id is plus _unhappy. For example:
<span id=​"textInput1_unhappy" class=​"unhappyMessage">​Please enter an email​</span>.

So all you have to do is list our your fields and any arbitrary test function for each. There are a few example validation functions built in. If you use underscore.js I'd suggest mixing in your validation functions into underscore like this.

Why Happy.js?

Yes, there a million form validation plugins already – but I like this approach and the good news is, if you don't, you have other options. In fact, if you want something really full-featured for jQuery. Use this one. Personally I wanted something really lightweight and extendable (because it's hard to be happy when you're bloated).

Available Options

Top level options are listed below. Only the fields attribute is required.

  1. fields (object, see below): The configs for each field with the jquery selector as the key.
  2. submitButton (string): If you pass jQuery selector to this the form will be validated when that item is clicked instead of on submit.
  3. happy (function): A callback that gets triggered when form submission is attempted and all fields pass validation.
  4. unHappy (function): A callback that gets triggered when form submission is attempted but any fields fail validation.
  5. errorTemplate (function): Used to generate custom error html instead of the default. Is passed a standard error object as its only parameter (which has id and message attributes). Should return the error message html.
  6. when (string: default: 'blur'): Event on which to reevaluate any field.
  7. classes (object, see below): The classes to set on the input fields and error messages for those fields.

Each field takes the following attributes all optional

  1. required (boolean or 'sometimes'): You can specify that a field is required here, OR... better yet specify it with the HTML5 required attribute like so: <input type="text" required>. Happy.js will detect that too, even in IE6. So either way is fine. Also, you can pass the string `'sometimes'`, to specify that you always want it to run the `test` function to determine validity. Otherwise 'Happy' will only validate non-blank values. Passing `'sometimes'` lets you make fields conditionally required.
  2. message (string): Message shown in case of an error for this field.
  3. test (function): A function that takes the field value as the first argument and returns true or false.
  4. arg (anything): An optional second argument that will get passed to the test function. This is useful for comparing with another paramter or whatnot. If this is a function it will be evaluated. This way you can compare it to something that is evaluated at runtime such as what they put in another field or to make a server call to check if a username is available, etc.
  5. clean (function): A function that is used to clean the data before it is validated. Note, this also writes the cleaned data back to the field input.
  6. trim (boolean, default: true): Password fields are not trimmed, but other field values are trimmed by default. Also, please note that if you pass a clean method it is assumed that you'll handle any trimming, etc, so the value won't be trimmed in that case.
  7. when (string, default: 'blur'): Event on which to reevaluate this field. Overrides top level 'when' setting for this field.

The classes parameter takes the following attributes all optional

  1. field (string, default: 'unhappy'): Class to apply to the input field on failed validation.
  2. message (string, default: 'unhappyMessage'): Class to apply to the error message for an input that has failed validation.

Examples

Full Working Example

<!doctype html>
<html>
  <head>
    <title>Demo</title>
    <script src="jquery.or.zepto.js"></script>
    <script src="happy.js"></script>
    <script src="happy.mytrimmedlistofmethods.js"></script>
    <script>
      $(document).ready(function () {
        $('#awesomeForm').isHappy({
          fields: {
            // reference the field you're talking about, probably by `id`
            // but you could certainly do $('[name=name]') as well.
            '#yourName': {
              required: true,
              message: 'Might we inquire your name'
            },
            '#email': {
              required: true,
              message: 'How are we to reach you sans email??',
              test: happy.email // this can be *any* function that returns true or false
            }
          }
        });
      });
    </script>
  </head>
  <body>
    <form id="awesomeForm" action="/lights/camera" method="post">
      <input id="yourName" type="text" name="name" />
      <input id="email" type="text" name="email" />
    </form>
  </body>
</html>

Credits

Happy.js was created by @HenrikJoreteg.

Documentation HTML/CSS created by Adam Brault.

Happy.js is currently being maintained by Michael Garvin

Other Contributors:

Tested in:

Happy.js has been tested in IE 6+, FF 3.6+, Chrome 7+, and Safari 5+. It should work in any browser that jQuery or Zepto supports

Changelog

from &yet