Skip to content
This repository has been archived by the owner on Aug 15, 2019. It is now read-only.

Commit

Permalink
fixed bug with validation response being false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
jackfranklin committed Nov 6, 2012
1 parent 2936d5b commit ae15aec
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 46 deletions.
66 changes: 47 additions & 19 deletions README.md
Expand Up @@ -8,7 +8,7 @@ This is _not_ a jQuery plugin, but does depend on jQuery.

## Demo

There's a demo included in the `demo/` folder.
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:

Expand Down Expand Up @@ -36,22 +36,30 @@ userForm.addValidation("shortname", { max_length: 5 });
Then when the form is submitted, see if those validations pass or not:

```javascript
$("form").on("submit", function(e) {
$("ul").html("");
e.preventDefault();
//now run your validations
var validationResult = userForm.runValidations();
if(validationResult.valid) {
$("h3").text("form validated!");
} else {
$("h3").text("Errors");
for(var i = 0; i < validationResult.messages.length; i++) {
var newLi = $("<li />", {
text: validationResult.messages[i]
}).appendTo("ul");
}
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:
Expand Down Expand Up @@ -161,16 +169,33 @@ The first is preferred but the second may be useful if you need to programatical
Clears all pending validations so none remain.

#### `runValidations(clearAfter)` returns `Object`
Runs all pending validations, returning a response object that's identical to `validateField`. Unlike `validateField`, this runs all pending validations on the _entire form_, across _all fields_.

__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:

```javascript
{
valid: true,
messages: []
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
}
}
}
```

Expand Down Expand Up @@ -330,6 +355,9 @@ If you make a pull request, please write tests for it :)

## Changelist

__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
Expand Down
16 changes: 15 additions & 1 deletion demo/demo.js
Expand Up @@ -11,17 +11,31 @@ $(function() {
$("form").on("submit", function(e) {
$("ul").html("");
e.preventDefault();

//now run your validations
var validationResult = userForm.runValidations();
if(validationResult.valid) {
$("h3").text("form validated!");
} else {
$("h3").text("Errors");
$("h3").text("All Errors:");
for(var i = 0; i < validationResult.messages.length; i++) {
var newLi = $("<li />", {
text: validationResult.messages[i]
}).appendTo("ul");
}

// or you can do errors on a field by field basis
for(var field in validationResult.fields) {
var fieldObj = validationResult.fields[field];
if(!fieldObj.valid) {
var errorSpan = $("<span />", {
"class" : "error",
"text" : fieldObj.messages.join(", ")
});
console.log(fieldObj);
fieldObj.html.after(errorSpan);
}
}
}
});

Expand Down
3 changes: 3 additions & 0 deletions demo/index.html
Expand Up @@ -5,6 +5,9 @@
<script src="../lib/jquery.js"></script>
<script src="../src/jquery.formvalidator.js"></script>
<script src="demo.js"></script>
<style>
.error { color: red; display: block; }
</style>
</head>
<body>
<form>
Expand Down
40 changes: 25 additions & 15 deletions dist/jquery.formvalidator.js
@@ -1,4 +1,4 @@
/*! jQuery Form Validator - v0.5.0 - 2012-11-04
/*! jQuery Form Validator - v0.6.0 - 2012-11-06
* https://github.com/jackfranklin/jQuery-Form-Validator
* Copyright (c) 2012 Jack Franklin; */

Expand All @@ -18,7 +18,7 @@

(function(window) {
var jFV = (function() {
var VERSION = "0.5.0";
var VERSION = "0.6.0";


// lets fields be passed in on init
Expand Down Expand Up @@ -59,14 +59,14 @@

var errorMessages = [];
for(var validation in validations) {
var method = validationMethods[validation];
var method = getValidationMethod(validation);
var params = validations[validation];
if(!method) { throw new Error("Validation method " + validation + " does not exist"); }
if(!method.fn(fieldValue, params, field.html)) {
errorMessages.push(replacePlaceholdersInMessage(method.message, { name: name, params: params }));
}
}
return { valid: (errorMessages.length < 1), messages: errorMessages };
return { valid: !(errorMessages.length), field: field, messages: errorMessages };
};


Expand Down Expand Up @@ -119,23 +119,33 @@
//ensure it's boolean true or false
clearAfter = !!clearAfter || false;

var response = { valid: true, messages: [] };

var fields = {};
var isValid = true;
for(var field in pendingValidations) {
//validate the field
var resp = validateField(field, pendingValidations[field]);
var respMessagesLen = resp.messages.length;
if(respMessagesLen) {
for(var i = 0; i < respMessagesLen; i++) {
response.messages.push(resp.messages[i]);
}
}
if(!resp.valid) { response.valid = false; }
fields[field] = { field: resp.field, messages: resp.messages, valid: resp.valid, html: resp.field.html };
}

if(clearAfter) { clearPendingValidations(); }
var allErrors = getAllErrors(fields);
return { valid: !allErrors.length, fields: fields, messages: getAllErrors(fields) };
};

return response;
/*fields object looks like:
* var fields = {
* username: {
* field: [ jQuery obj],
* messages: [ array of error messages ],
* valid: true/false // if that field passed its validations
* }
* }
*/
var getAllErrors = function(fieldsObj) {
var allErrors = [];
for(var field in fieldsObj) {
allErrors = allErrors.concat(fieldsObj[field].messages);
}
return allErrors;
};

//object that we store all the validations in - this object is not exposed publically
Expand Down
4 changes: 2 additions & 2 deletions dist/jquery.formvalidator.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -2,7 +2,7 @@
"name": "jquery.formvalidator",
"title": "jQuery Form Validator",
"description": "A Form Validator library",
"version": "0.5.0",
"version": "0.6.0",
"homepage": "https://github.com/jackfranklin/jQuery-Form-Validator",
"author": {
"name": "Jack Franklin",
Expand Down
12 changes: 6 additions & 6 deletions src/jquery.formvalidator.js
Expand Up @@ -22,7 +22,7 @@

(function(window) {
var jFV = (function() {
var VERSION = "0.5.0";
var VERSION = "0.6.0";


// lets fields be passed in on init
Expand Down Expand Up @@ -63,7 +63,7 @@

var errorMessages = [];
for(var validation in validations) {
var method = validationMethods[validation];
var method = getValidationMethod(validation);
var params = validations[validation];
if(!method) { throw new Error("Validation method " + validation + " does not exist"); }
if(!method.fn(fieldValue, params, field.html)) {
Expand Down Expand Up @@ -124,15 +124,15 @@
clearAfter = !!clearAfter || false;

var fields = {};
var isValid = true;
for(var field in pendingValidations) {
//validate the field
var resp = validateField(field, pendingValidations[field]);
if(!resp.valid) {
fields[field] = { field: resp.field, messages: resp.messages, valid: !resp.messages.length };
}
fields[field] = { field: resp.field, messages: resp.messages, valid: resp.valid, html: resp.field.html };
}
if(clearAfter) { clearPendingValidations(); }
return { valid: !Object.keys(fields).length, fields: fields, allMessages: getAllErrors(fields) };
var allErrors = getAllErrors(fields);
return { valid: !allErrors.length, fields: fields, messages: getAllErrors(fields) };
};

/*fields object looks like:
Expand Down
7 changes: 5 additions & 2 deletions test/spec/formvalidatorSpec.js
Expand Up @@ -236,16 +236,19 @@ describe("jQuery Form Validator", function() {

var validationResp = validationTest.runValidations();
expect(validationResp.valid).toEqual(false);
expect(validationResp.allMessages.length).toEqual(2);
expect(validationResp.messages.length).toEqual(2);
expect(validationResp.fields.email.messages.length).toEqual(1);
expect(validationResp.fields.username.valid).toEqual(false);
});
it("can add validations for same field multiple times", function() {
validationTest.addValidationMethod("exact_length", function(val, arg) {
return val.length == arg;
}, "Field %F has to be %ARG characters");
validationTest.addValidation("username", { exact_length: 5 });
validationTest.addValidation("username", { matches: "jackf" });

// check that its valid
$(validationTest.field("username").html).val("jackf");
validationTest.field("username").html.val("jackf");
var validationResp = validationTest.runValidations();
expect(validationResp.valid).toEqual(true);

Expand Down

0 comments on commit ae15aec

Please sign in to comment.