Happy.js: Lightweight form validation for jQuery or Zepto.js

Happy.js: Lightweight form validation for jQuery or Zepto.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.

Usage

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>

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
      }
    }
  });

Happy.js will now validate individual fields on blur events and all fields on submit. If validation fails two things happen:
- The field will get an unhappy class (yes, I’m quite serious).
- The field will get a 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.

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>


Documentation and download

Related articles