Pre parsing validation
I've read the following issue: #166 and I'm wondering how we can enforce type validation (using is module or node-validator).
If you submit an object to a string field, it is viewed as valid ("[Object object]"). Of course, I don't think it is the desired behaviour. What do you think about it?
Or maybe providing a generic field and we add this kind of validation:
exports.typeValidator = function (type, message) {
if(!is.fn(is[type])) {
throw new TypeError('this type is not defined');
}
var msg = message || 'Please enter a valid value';
return function (form, field, callback) {
if (is[type](field.data)) {
callback();
} else {
callback(msg);
}
};
};
Forms are used to validate values sent over the wire - how can you submit an object value to it?
I'm definitely on board with adding is-based validation, but I'm not sure I understand where it would be valuable.
In other words, the [object Object] conversion likely happens in the browser, long before forms comes into play.
Ok. I understand. I explain my use case. It's a simple REST API used with an SPA (AngularJS). As usual, I don't trust frontend submission and I use this lib to parse the JSON input and validate it. So, I need to care about the field type. Perhaps it is not the main use case but I've found this lib very useful, I'm trying to find some solution to make it more powerful ;)
I'm all about adding explicit is.string and such tests - i don't like is[type] though.
If I have a field foo then some form data parsers will parse a posted field foo[bar]=abc as { bar: 'abc' }. That's eg. the default in PHP.
And foo=abc&foo=xyz is by some parsers parsed as ['abc', 'xyz'], so it is possible to get objects and arrays out of fields that weren't intended to be that, all depending on ones parser – and since one will often be using a parser outside of forms itself, it all depends on how one configures it.
And now after writing this I realize that you are the maintainer of one of the major such parsing libraries @ljharb: https://github.com/ljharb/qs 😅
Would it maybe be better to ignore the data when parsing, rather than type casting it?
https://github.com/caolan/forms/blob/3fb0edce7d1f7831e616f95ee7807c76e680e0d0/lib/fields.js#L24-L26
https://github.com/caolan/forms/blob/3fb0edce7d1f7831e616f95ee7807c76e680e0d0/lib/fields.js#L114-L119
Or maybe even throw an exception if the data is set, but is set to something else than a string in eg. those two cases?