• This repository has been archived on 16/Aug/2019
  • Stars
    star
    233
  • Rank 172,230 (Top 4 %)
  • Language
    JavaScript
  • Created about 12 years ago
  • Updated almost 12 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Got bored of using other ones, so made my own

jQuery Form Validator

I got bored of using other people's validators that didn't work just as I wanted.

So I created one.

This is not a jQuery plugin, but does depend on jQuery.

Demo

There's a demo included in the demo/ folder. If you're not sure on the documentation, you should look at the demo first. It contains a pretty solid example on how to use the library. All the main methods are also covered in the tests, so between this document, the demo and the tests, you should be set. Any problems, raise an issue or tweet @Jack_Franklin.

The basic idea goes, that you have a HTML form:

<form>
  Username: <input type="text" name="username" />
  Short Name: <input type="text" name="shortname" />
  <input type="submit" value="go" />
</form>

And you set up your validator and add some validations:

var userForm = window.FormValidator($("input[type='text']"));

//add your validations
userForm.addValidation("username", {
  min_length: 6,
  required: true
});
userForm.addValidation("shortname", { max_length: 5 });

Then when the form is submitted, see if those validations pass or not:

var validationResult = userForm.runValidations();
if(validationResult.valid) {
  $("h3").text("form validated!");
} else {
  //you might just want to loop through all errors from all fields and display them:
  $("h3").text("All Errors:");
  for(var i = 0; i < validationResult.messages.length; i++) {
    var newLi = $("<li />", {
      text: validationResult.messages[i]
    }).appendTo("ul");
  }

  //or loop through the errors for each field, and add them just after the field in a span tag:
  for(var field in validationResult.fields) {
    var fieldObj = validationResult.fields[field];
    if(!fieldObj.valid) {
      var errorSpan = $("<span />", {
        "class" : "error",
        "text" : fieldObj.messages.join(", ")
      });
      fieldObj.html.after(errorSpan);
    }
  }
}

You can add your own validation methods too:

.addValidationMethod("exact_length", function(val, arg) {
  return val.length == arg;
}, "Field %F has to be %ARG characters");

These are further documented below.

Once a field is added, you can also get at its attributes and a jQuery object containing the element (not particularly useful but may come in handy).

console.log(userForm.field("username").attributes); //=> { name: "username" type: "text" }
console.log(userForm.field("username").html); //=> [ <input type="text" name="username"> ]

Documentation

If anything's not clear, the best place to look is the tests. Every public method is tested in there.

Getting started

Create a new variable to store your form in:

var signUpForm = FormValidator();

Then call methods on signUpForm:

Dealing with Fields

addField(field)

Adds a field to the form validator, that you can then validate against. Argument can either be any valid CSS selector (any that you would pass into jQuery), or a jQuery object. If the jQuery object has multiple elements, only the first will be saved. Field is added to the internal fields object, which are index by the field's name attribute.

addFields(fields)

Same as addField, but handles multiple elements passed in. Either pass in an array of CSS selectors, or a jQuery object.

field(name) returns Object

Pass in a string which is the name of the field, and you get an object back representing it. Rarely useful. Response:

{
  html: [ <input type="text" name="foobar" /> ],
  attributes: {
    type: "text",
    name: "foobar"
  }
}

You can combine the adding of fields with the initial step. For example, instead of:

var signupForm = FormValidator();
signupForm.addFields(foo);

You can do:

var signupForm = FormValidator(foo);

Adding and Running Validations

validateField(name, validations) returns Object

Takes the field name and an object of validations, and runs them, returning the response. For example:

validateField("username", {
  min_length: 5,
  required: true
});

//returns
{
  valid: true, //if the validations passed or failed
  messages: [] //any error messages that were returned
}

addValidation(name, validations)

Works identically to validateField with one key exception. It adds a validation but doesn't run it. You can also add multiple validations in two different ways. Either:

addValidation("username", {
  min_length: 5,
  required: true
});

or

addValidation("username", { min_length: 5 });
addValidation("username", { required: true });

The first is preferred but the second may be useful if you need to programatically add validations at different times.

clearPendingValidations()

Clears all pending validations so none remain.

runValidations(clearAfter) returns Object

New in 0.6: returns a more complex object with each field's messages individually, along with the field's jQuery object.

Runs all pending validations, returning a response object.

If you pass in an argument of true, it clears the pending validations object completely.

The response is like so:

{
  valid: true, //boolean true or false, if the entire validation set was valid
  messages: [], //array of error messages of all fields combined
  fields: {
    username: {
      field: { //the same object you would get from calling yourForm.field("username")
        html: [ <input type="text" name="username" /> ],
        attributes: {
          type: "text",
          name: "username"
        }
      },
      messages: [], //error messages for just that field
      valid: true, //boolean true/false for if THAT field was valid or not
      html: [ <input type="text" name="username" />] //jQuery object for that field. A shortcut to the html property of the field object
    }
  }
}

getPendingValidations returns Object

Returns the pending validations as a key-value object, with the key being the field name, and the value being the validation string. Sample response:

{
  username: {
    min_length: 4,
    required: true
  },
  email: {
    max_length: 20
  }
}

Not used particularly often.

Validation Methods

Right now only a few validation methods exist out of the box. They are:

  • min_length(x) the value must have at least x characters
  • max_length(x) the value can have up to x characters
  • required the value cannot be blank
  • length_between(x,y) value must have at least x characters but no more than y
  • matches(str) value must match str exactly.

There are more to come, but until then, if you end up writing some, please post them on Github and I'll happily pull them in.

There's also methods to add validations.

addValidationMethod(name, obj)

Pass in the validation name and an object of properties.

var new_matches = {
  message: "Field %F must equal %ARG",
  fn: function(val, arg) {
    return val == arg;
  }
}
addValidationMethod('matches', new_matches);

name is the name you'll refer to when adding validations to a field. obj should contain two fields: fn is the function that's run to test the validation. It's passed three arguments:

  • the value of the field you're validating against
  • the parameter(s) it's called with
  • a jQuery object containing the field It's unlikely you'll ever use the third parameter, but it's there if you need it. A validation method just needs to return true or false.

message is the method's error message. These contain placeholders, which are documented below.

For example, the min_length validation function looks like so:

function(val, arg) {
  return val.length >= arg;
},

Because I know min_length will only take one argument, I can just reference the variable passed in. Validation methods are only passed in an array of arguments if they take more than one. If they only take one, that one value is passed in. Compare the above to the length_inbetween validator:

length_between: {
  message: "Field %F must be a minimum of %ARGS[0] characters and a maximum of %ARGS[1]",
  fn: function(val, args) {
    var len = val.length;
    return (len >= args[0] && args[1] >= len);
  }
}

Notice how I don't even bother referencing the 3rd argument, as I wont need it. Usually just the field's value is all you'll need.

message is the error message that is returned if the validation fails. This is just a string, but it has a couple of placeholders. %F is used to show where the field name will go in the string.

If your validation method takes one parameter, use %ARG in the message string as a placeholder as to where that will go. For example, here's the min_length message:

Field %F must be at least length %ARG"

If your validation method takes >1 arguments, refer to the arguments as %ARGS[0], %ARGS[1] and so on. For example, here's the length_between message:

Field %F must be a minimum of %ARGS[0] characters and a maximum of %ARGS[1]

Here's an example of how I'd add an exact_length validator:

addValidationMethod("exact_length", {
  fn: function(val, arg) {
    return val.length == arg;
  },
  message: "Field %F has to be %ARG characters"
});

Which could then be used as { exact_length: 6 }

Changing Validation Messages

It's likely that you might want to change the built in messages that come out of the box. You can do this through two methods:

getValidationMethod(name) returns Object

Returns an object that represents a validator. Example:

getValidationMethod("matches")

Returns:

{
  message: "Field %F must match %ARG",
  fn: function(val, arg) {
    return val == arg;
  }
}

addValidationMethod(name, obj)

Pass in the validation name and an object to save it:

var new_matches = {
  message: "Field %F must equal %ARG",
  fn: function(val, arg) {
    return val == arg;
  }
}

saveValidationMethod("matches", new_matches);

And that's it! A good place to start is demo/demo.js, which has a plain example to get you going in the right direction.

Contributing

This project uses Grunt JS for testing, linting and deploying.

Install Grunt JS: npm install -g grunt

Then clone and cd into this repository and run npm install.

Now you should be able to run grunt to lint, test, concatenate and minify.

Tests are written in Jasmine and can be tested with grunt jasmine.

You can run linting with grunt lint.

Run lints and tests with grunt test.

If you make a pull request, please write tests for it :)

Contributors

  • @jackfranklin
  • @joshstrange

Todo

  • Add NodeJS support
  • test and document cross-browser support

Changelog

Version 0.9.2

  • added fields() method, which returns the fields object of a JFV instance.

Version 0.9.1

  • add methods to JFV.prototype, not just to the JFV object.

Version 0.9

  • support AMD libraries like RequireJS.
  • switch to using proper semantic versioning (from this point on)
  • generated a Docco build file (see docs/).
  • rewrote library as a JS class (public API usage hasn't changed)
  • support validating checkboxes as well as text fields

Version 0.6

  • changed the response object to return each field and its error messages indidividually - thanks @joshstrange for the initial idea and some of the code.

Version 0.5

  • Fixed a typo in the README - thanks @joshstrange
  • use Regex to replace within messages - thanks @joshstrange
  • Integrated into Grunt JS (see section on Contributing)

Version 0.4

  • made it onto Hacker News!
  • thanks to a suggestion on there, ditched using strings for validations and switched to JS objects, which make much more sense. So, instead of:
addValidation("username", "min_length(5)|required");

It's now:

addValidation("username", { min_length: 5, required: true });

A few things have changed as a by-product of this - please do read the docs carefully. Any questions please ask away!

Version 0.3

  • rewrote the validation methods so they are passed in three arguments: value, args, obj. Realised most methods will only care about the field value, so pass that in directly rather than just the object to streamline the validation methods. Object is passed in as 3rd argument if it is needed.

Version 0.2

  • ability to add fields through the FormValidator method.
  • runValidations takes optional argument which, if set to true, will clear pending validations once run.
  • added getPendingValidations method.

Version 0.1

  • first release!

More Repositories

1

gulp-load-plugins

Automatically load in gulp plugins
JavaScript
756
star
2

test-data-bot

TypeScript
666
star
3

dotfiles

My dotfiles for my dev environment, compromising of tmux, vim, zsh and git.
Lua
235
star
4

pulldown

The minimal JavaScript package manager.
JavaScript
175
star
5

demopack

A prepackaged Webpack for easy frontend demos.
JavaScript
172
star
6

remote-data-js

Dealing with remote data and all its states properly in JavaScript applications.
JavaScript
149
star
7

universal-react-example

An example Universal ReactJS application
JavaScript
144
star
8

the-refactoring-tales

HTML
138
star
9

tilvim

TIL Vim: Short posts on Vim tips and tricks
HTML
89
star
10

tweet-parser

Parsing tweets into lists of entities.
JavaScript
76
star
11

react-css-modules-webpack

React + Webpack Dev Server + Hot Reloading + CSS Modules
JavaScript
72
star
12

jspm-es6-react-example

JavaScript
69
star
13

fetch-factory

Easy JS objects for talking to your APIs
JavaScript
67
star
14

jspm-dev-builder

Incremental development builds with jspm
JavaScript
66
star
15

elmplayground

An Elm blog, written in Elm, about Elm.
Elm
63
star
16

react-remote-data

JavaScript
57
star
17

so-fetch

TypeScript
57
star
18

html-dist

A tool for editing HTML files to add new scripts
JavaScript
47
star
19

javascriptplayground.com

HTML
39
star
20

react-hot-load-webpack-boilerplate

JavaScript
37
star
21

doccy

Generate Markdown documentation from JavaScript
JavaScript
31
star
22

elm-for-js-developers-talk

Elm
30
star
23

vue2-demo-proj

JavaScript
28
star
24

react-training-workshop

Code, notes and more for a day long React workshop.
JavaScript
27
star
25

todo-react-testing

A silly small React TODO app used in a blog post about testing React apps.
JavaScript
25
star
26

rollup-plugin-markdown

JavaScript
23
star
27

react-no-webpack-required

Using React without Babel & Webpack
JavaScript
22
star
28

do-you-even-elm

How much Elm do you do?
Elm
21
star
29

node-todo

A Node.js & Express.js todo app
JavaScript
19
star
30

vscode-go-to-file

TypeScript
18
star
31

svg-to-elm

TypeScript
17
star
32

Forrst-API-jQuery-Wrapper

A jQuery wrapper for the Forrst API. As the Forrst API grows, so will this.
JavaScript
17
star
33

elm-boilerplate

Starting point for Elm-Lang projects
JavaScript
17
star
34

interactive-es6

Learn ES6 in your browser in an app built in ES6.
JavaScript
16
star
35

responsiveImages

Responsive Images in JavaScript!
CoffeeScript
16
star
36

jspm-es6-example

JavaScript
16
star
37

doubler

Simple doubles for JS testing
JavaScript
14
star
38

react-ast-viewer

An Abstract Syntax Tree browser, written in React
JavaScript
14
star
39

pure-react-forms

JavaScript
14
star
40

JavaScript-Playground--Simple-jQuery-PubSub

Code for the blog post on JavaScriptPlayground.com on a simple jQuery PubSub
JavaScript
13
star
41

cannon-blog

A ReactJS blogging engine
JavaScript
13
star
42

jspm-es6-angular-example

JavaScript
13
star
43

totesy

My own TODO app
JavaScript
12
star
44

elm-game-of-life

Building Conway's Game of Life in Elm
Elm
12
star
45

JS-Regex

Live JS Regular Expression Testing
JavaScript
12
star
46

prettier-scripts

Some shell scripts for Prettier.
JavaScript
12
star
47

github-proxy

GitHub API but cached and offline-able.
JavaScript
11
star
48

authoring-es6-module-example

JavaScript
10
star
49

node_cli_router

A router for parsing command line flags and arguments in your Node CLI scripts.
JavaScript
9
star
50

wouldlike.js

JavaScript
8
star
51

client-webpack-boilerplate

A teeny client side JS webpack boilerplate to get up and running quickly.
JavaScript
8
star
52

react-fundamentals-2019-workshop

JavaScript
7
star
53

skillswap

Share your skills with others and find people to help you learn new things.
JavaScript
7
star
54

half-stack-webpack

JavaScript
7
star
55

zip-list

TypeScript
7
star
56

testing-react-with-jest

JavaScript
7
star
57

react-introduction-exercises

JavaScript
7
star
58

universal-react-talk

JavaScript
7
star
59

jQuery-UK-2012-Conference-Notes

6
star
60

elm-github-info

Fetching info from GitHub using Elm
Elm
6
star
61

ST2-MDN-Search

Search the MDN from within Sublime Text 2
Python
6
star
62

ng2-jspm-typescript

JavaScript
6
star
63

vim-markdown-writer

Some Vim functions to make writing blog posts in Markdown easier.
Vim Script
6
star
64

introduction-to-elm-workshop

Elm
5
star
65

elm-statey

A state machine library in Elm
Elm
5
star
66

elm-json-decoding

Elm
5
star
67

rollup-plugin-import-glob

JavaScript
5
star
68

advent-of-code-2018

Elm
5
star
69

angular-router-browserify

Angular's router module to be used with browserify.
JavaScript
4
star
70

project_templater

A gem for quickly creating project structures.
Ruby
4
star
71

githubissuebrowser

Browse all issues across your repositories to find something to work on.
Ruby
4
star
72

ecmascript-evaluator

JavaScript
4
star
73

JS-Instagram-Wrapper

JavaScript
4
star
74

HTML5-Placeholder-PolyFill

Adds placeholder functionality to input fields in browsers that don't support HTML5 Placeholders
JavaScript
4
star
75

london-elm-018-talk

JavaScript
4
star
76

jspm-test

Browser test runner for jspm projects
JavaScript
4
star
77

elm-console-log

An easier log function for Elm.
Elm
4
star
78

react-webpack-boilerplate

JavaScript
4
star
79

testing-javascript-workshop

JavaScript
3
star
80

elm-connect-four

Connect 4 written in Elm
Elm
3
star
81

jQuote

3
star
82

epic-fel-es6-today-links

3
star
83

devcastin

Ruby
3
star
84

beginning-react

HTML
3
star
85

jack-sublime-snippets

3
star
86

jQuery-Split-List

Splits lists in half
JavaScript
3
star
87

Base-Template

A starting point for all my development.
JavaScript
3
star
88

reactjs-workshop

Code and notes for a ReactJS workshop
JavaScript
3
star
89

Deck.js---Gamepad-API

Deck.js slideshows controlled with the Gamepad API
JavaScript
3
star
90

jsFrame

Combining a jQuery Plugin with a CSS Grid for lovely coding.
JavaScript
3
star
91

MarkdownTwitter

Automatically linking Twitter mentions in Markdown blog posts
Ruby
2
star
92

jackfranklindotcodotuk

JavaScript
2
star
93

frontendlondonfeb2015-jspm-demo

JavaScript
2
star
94

CoffeePubSub

A very small Pub/Sub implementation in CoffeeScript
CoffeeScript
2
star
95

Back-to-Top-Firefox-Plugin

An easy way to get back to the top of any webpage in Firefox.
JavaScript
2
star
96

util-fns

JavaScript
2
star
97

interactive-react

JavaScript
2
star
98

rash

Ruby hash methods in JavaScript
JavaScript
2
star
99

Big-M-Workshop-Notes

2
star
100

langtons-ant-elm

It's an ant innit.
Elm
2
star