This project is no longer maintained.
See it in action at http://cojomojo.github.io/Crystal.js/
- 4KB minified
- No JQuery.
-
Download or clone Crystal.js and include it in your HTML markup.
<script type='text/javascript' src='/path/to/crystal.min.js'></script>
-
Add the necessary HTML markup to input and textarea elements you want to apply Crystal to. You'll just have to add a data attribute
data-crystalwith the value begin the kind of field it is (e.g. a name field, email, etc.). You'll be creating validation rules using this value later on.<input data-crystal="name" type="text">
-
Add the CSS
.crystal-invalid { border: 2px solid #f15b22 !important; }
-
Instantiate Crystal. The constructor takes one parameter, the parent node for all forms you want to apply Crystal to. By default this is
document.var crystal = new Crystal(); // OR somethiing like this var crystal = new Crystal(document.getElementById("demo1"));
The flexibility of Crystal.js is because it allows for you to define the validation rules. It is very simple, just use the method setCrystalFieldConfig.
/**
* Sets the configurable parts of the
* @param {int | int array | "all"} [id] the "data-crystal-id"(s) of the element(s) to set the config for
* @param {string} the "data-crystal" value you want to create validation for
* @param {config} an object with the following params
* @param {regex literal} [regex] Regex literal to test input value agains. You want this to match valid input
* @param {input|blur} [trigger] Event that determines when fields are checked for validity. Defaults to "input".
*/
crystal.setCrystalFieldConfig("all", "name", {
regex: /^(?!\s*$).+/,
});Check out these awesome validation configurations for some common fields like name, email, and message.
The next thing you will want to do is decide what will happen if a user submits a form when fields are valid or invalid. Crystal.js proivdes an event emitter to make handling this easy. Check out this example (setup for this site's home page):
crystal.ee.on("form-1-valid", function(el) {
alert("Message Sent");
});
crystal.ee.on("form-1-invalid", function(el) {
document.getElementById("not-valid").style.display = "block";
});Note that when a form's submit button is pressed, and a field is invalid, preventDefault()is applied.
As you can see, each form emits it's own event. The events are dynamically named like so "form-(data-crystal-id)-valid" and "form-(data-crystal-id)-invalid".
Crystal.js can be very powerful. Check out the GitHub Wiki for the complete and in depth documentation.
The goal of Crystal.js is to be a boilerplate for awesome inline form validation. This should be kept in mind when contributing. Pull the dev branch, contribute, and submit a pull request!
MIT