Permalink
Browse files

Add form.

  • Loading branch information...
1 parent 7346f74 commit abe3ac237eb3c2ced6a6a856ea784aaaf1ec2958 @jone jone committed Feb 26, 2012
Showing with 85 additions and 0 deletions.
  1. +22 −0 form.css
  2. +6 −0 form.js
  3. +28 −0 index.html
  4. +29 −0 validator.js
View
22 form.css
@@ -0,0 +1,22 @@
+.fields {
+ list-style-type: none;
+}
+
+.fields li {
+ padding: 0.5em;
+ margin-bottom: 2em;
+}
+
+.fields label {
+ display: block;
+}
+
+.fields li.erroneous {
+ border: 1px solid #FAA;
+ background-color: #FEE;
+}
+
+.fields li.erroneous div.error {
+ color: #F33;
+ padding-top: 0.2em;
+}
View
6 form.js
@@ -0,0 +1,6 @@
+$(document).ready(function($) {
+
+ initializeValidators({
+ 'integer-field': buildIntValidator});
+
+});
View
28 index.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Form validator</title>
+ <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
+ <script src="validator.js" type="text/javascript" ></script>
+
+ <script src="form.js" type="text/javascript"></script>
+ <link href="form.css" rel="stylesheet" type="text/css"/>
+ </head>
+
+ <body>
+
+ <h1>Form validator</h1>
+
+ <form action="#">
+
+ <ul class="fields">
+ <li>
+ <label for="integer-field">Integer Field</label>
+ <input type="text" id="integer-field" />
+ </li>
+ </ul>
+
+ </form>
+ </body>
+
+</html>
View
29 validator.js
@@ -1,3 +1,32 @@
+function initializeValidators(fieldValidatorMap) {
+ $.each(fieldValidatorMap, function(fieldId, validatorFun) {
+ $('#'.concat(fieldId)).each(function(i, field) {
+ var validator = validatorFun(field);
+ registerValidatorEventHandler($(field), validator);
+ });
+ });
+}
+
+function registerValidatorEventHandler(field, validator) {
+ field.change(function() {
+ var container = field.parents('li:first');
+ container.find('.error').remove();
+
+ var errors = [];
+ var valid = validator.valid(errors);
+
+ if(!valid) {
+ container.addClass('erroneous');
+ $(errors).each(function(i, msg) {
+ $('<div class="error" />').text(msg).appendTo(container);
+ });
+ } else {
+ container.removeClass('erroneous');
+ }
+
+ });
+}
+
function buildIntValidator(field) {
return {
valid: function(errors) {

0 comments on commit abe3ac2

Please sign in to comment.