Lightweight form validation for jQuery or Zepto.js
Or... you can clone the whole project from GitHub with Git by running:
$ git clone git://github.com/henrikjoreteg/Happy.js
<form id="awesomeForm" action="/lights/camera" method="post">
<input id="yourName" type="text" name="name" />
<input id="email" type="text" name="email" />
</form>
$('#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, false, or an instance of Error
}
}
});
That's it. Happy.js will now validate individual fields on blur events and all fields on submit. If validation fails two things happen:
unhappy
class (yes, I'm quite serious).<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.
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).
Top level options are listed below. Only the fields
attribute is required.
fields
(object, see below): The configs for each field with the jquery selector as the key.
submitButton
(string): If you pass jQuery selector to this the form will be validated when that item is clicked instead of on submit.
happy
(function): A callback that gets triggered when form submission is attempted and all fields pass validation.
unHappy
(function): A callback that gets triggered when form submission is attempted but any fields fail validation.
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.
when
(string: default: 'blur'): Event on which to reevaluate any field.
classes
(object, see below): The classes to set on the input fields and error messages for those fields.
errorTarget
(string): Selector to use in lieu of the input element itself when choosing where to insert the error html. Error html will be inserted .after() this selector
Each field takes the following attributes all optional
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.
message
(string): Message shown in case of an error for this field.
test
(function): A function that takes the field value as the first argument and returns true
, false
, or an instance of Error
. Returning an instance of Error
will fail the test.
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.
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.
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.
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
field
(string, default: 'unhappy'): Class to apply to the input field on failed validation.
message
(string, default: 'unhappyMessage'): Class to apply to the error message for an input that has failed validation.
<!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, false, or an instance of Error
},
'#birthday': {
required: true,
message: 'Please provide a valid birth date.',
test: function(value) {
var birthday = new Date(value);
var birthdayInt = birthday.getTime();
if (isNaN(birthdayInt)) {
// uses the default message.
return false;
}
if(birthdayInt > new Date()) {
return new Error('Your birthday must have already happened.');
}
if (birthday.getDay() === 3) {
return new Error('Your birthday cannot have happened on a Wednesday.');
}
return true;
}
}
}
});
});
</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>
Happy.js was created by @HenrikJoreteg.
Documentation HTML/CSS created by Adam Brault.
Happy.js is currently being maintained by Michael Garvin
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