Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remote validator. #127

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ For integrating with Twitter bootstrap 3 (horizontal form), this is what you nee
});

var bootstrapField = function (name, object) {

object.widget.classes = object.widget.classes || [];
object.widget.classes.push('form-control');

Expand Down Expand Up @@ -173,7 +172,7 @@ components following the same API.
* multipleSelect
* label

### Validators
### Field validators

* matchField
* matchValue
Expand All @@ -194,6 +193,10 @@ components following the same API.
* digits
* integer

### Form validators

* async

### Renderers

* div
Expand All @@ -217,6 +220,41 @@ Forms can be created with an optional "options" object as well.
* `validatePastFirstError`: `true`, otherwise assumes `false`
* If `false`, the first validation error will halt form validation.
* If `true`, all fields will be validated.
* `validators`: form validators. An example:

```
var forms = require('forms'),
fields = forms.fields,
validators = forms.validators;

var options = {
validators = [
validators.async(function(data, next) {

// eg. post request.

var err = null;
var response = {
username: {
error: 'User with that name already exists.',
value: 'qwe'
},
password: {
error: 'Password is to short.',
value: 123
}
};

next(err, response);
})
]
};

var reg_form = forms.create({
username: fields.string(),
password: fields.password()
}, options);
```


### Form object
Expand Down Expand Up @@ -347,7 +385,7 @@ Returns a string containing a HTML representation of the widget for the given
field.


### Validator
### Field Validator

A function that accepts a bound form, bound field and a callback as arguments.
It should apply a test to the field to assert its validity. Once processing
Expand All @@ -369,4 +407,3 @@ containing a HTML representation of the field.
[7]: https://nodei.co/npm/forms.png?downloads=true&stars=true
[8]: https://npmjs.org/package/forms
[9]: http://vb.teelaun.ch/caolan/forms.svg

1 change: 0 additions & 1 deletion lib/fields.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,3 @@ exports.date = function (opt) {
exports.object = function (fields, opts) {
return forms.create(fields || {});
};

18 changes: 15 additions & 3 deletions lib/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ exports.create = function (fields, opts) {
var b = {};
b.toHTML = f.toHTML;
b.fields = {};
b.validators = f.validators || [];

Object.keys(f.fields).forEach(function (k) {
if (data != null) {
b.fields[k] = f.fields[k].bind(data[k]);
Expand All @@ -53,7 +55,17 @@ exports.create = function (fields, opts) {
callback(validatePastFirstError ? null : err);
});
}, function (err) {
callback(err, b);
if (err) {
return callback(err, b);
}

async.forEach(b.validators, function (validator, callback) {
validator(b, function (err) {
callback(validatePastFirstError ? null : err);
});
}, function (err) {
callback(err, b);
});
});
};
b.isValid = function () {
Expand Down Expand Up @@ -111,8 +123,8 @@ exports.create = function (fields, opts) {
var kname = is.string(name) ? name + '[' + k + ']' : k;
return html + form.fields[k].toHTML(kname, iterator);
}, '');
}
},
validators: opts.validators
};
return f;
};

13 changes: 12 additions & 1 deletion lib/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ exports.required = function (message) {
};
};

exports.async = function (asyncFunction) {
return function (form, callback) {
asyncFunction(form.data, function (err, response) {
Object.keys(form.fields).forEach(function (fieldName) {
form.fields[fieldName].error = response[fieldName].error;
form.fields[fieldName].value = response[fieldName].value;
});
callback(err, form);
});
};
};

exports.requiresFieldIfEmpty = function (alternate_field, message) {
if (!message) { message = 'One of %s or %s is required.'; }
var validator = function (form, field, callback) {
Expand Down Expand Up @@ -210,4 +222,3 @@ exports.digits = function (message) {
exports.integer = function (message) {
return exports.regexp(/^-?\d+$/, message || 'Please enter an integer value.');
};

85 changes: 84 additions & 1 deletion test/test-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,90 @@ test('validate invalid data', function (t) {
});
});

test('validate valid data with form validator', function (t) {
t.plan(2);
var fields = {
field1: forms.fields.string(),
field2: forms.fields.string()
};

var options = {
validators: [
function (form, next) {
setTimeout(function () {
form.fields.field1.value = 'field1 value';
form.fields.field1.error = null;
form.fields.field2.value = 'field2 value';
form.fields.field2.error = null;

next(null, form);
}, 100);
}
]
};

var f = forms.create(fields, options);

f.bind({field1: '1', field2: '2'}).validate(function (err, f) {
t.equal(f.isValid(), true);
t.equal(
f.toHTML(),
'<div class="field">' +
'<label for="id_field1">Field1</label>' +
'<input type="text" name="field1" id="id_field1" value="field1 value" />' +
'</div>' +
'<div class="field">' +
'<label for="id_field2">Field2</label>' +
'<input type="text" name="field2" id="id_field2" value="field2 value" />' +
'</div>'
);
t.end();
});
});

test('validate invalid data with form validator', function (t) {
t.plan(2);
var fields = {
field1: forms.fields.string(),
field2: forms.fields.string()
};

var options = {
validators: [
function (form, next) {
setTimeout(function () {
form.fields.field1.value = 'wrongInput1';
form.fields.field1.error = 'validation error 1';
form.fields.field2.value = 'wrongInput2';
form.fields.field2.error = 'validation error 2';

next(null, form);
}, 100);
}
]
};

var f = forms.create(fields, options);

f.bind({field1: '1', field2: '2'}).validate(function (err, f) {
t.equal(f.isValid(), false);
t.equal(
f.toHTML(),
'<div class="field error">' +
'<p class="error_msg">validation error 1</p>' +
'<label for="id_field1">Field1</label>' +
'<input type="text" name="field1" id="id_field1" value="wrongInput1" />' +
'</div>' +
'<div class="field error">' +
'<p class="error_msg">validation error 2</p>' +
'<label for="id_field2">Field2</label>' +
'<input type="text" name="field2" id="id_field2" value="wrongInput2" />' +
'</div>'
);
t.end();
});
});

test('handle empty', function (t) {
t.plan(3);
var f = forms.create({field1: forms.fields.string()});
Expand Down Expand Up @@ -444,4 +528,3 @@ test('div bound error', function (t) {
t.end();
});
});

39 changes: 39 additions & 0 deletions test/test-validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,3 +427,42 @@ test('digits', function (t) {
t.end();
});

test('async', function (t) {
t.test('validator should process response to form object properly', function (st) {
var data = {
fields: {
field1: {data: 'invalid value'},
field2: {data: 'valid value'}
}
};

var asyncFunction = function (data, next) {
var err = null;
var response = {
field1: {
error: 'validation message',
value: 'invalid value'
},
field2: {
error: null,
value: 'valid value'
}
};

next(err, response);
};

var v = validators.async(asyncFunction);
st.plan(4);
v(data, function (err, form) {
st.equal(form.fields.field1.error, 'validation message');
st.equal(form.fields.field1.value, 'invalid value');
st.equal(form.fields.field2.error, null);
st.equal(form.fields.field2.value, 'valid value');

st.end();
});
});

t.end();
});