ansman / validate.js

A declarative validation library written javascript
https://validatejs.org
MIT License
2.63k stars 336 forks source link

validation return values only as String? #62

Closed helt closed 9 years ago

helt commented 9 years ago

Is it intended behaviour that custom validators return only strings? I have written a slightly more complex validator, which checks whether date ranges do overlap or not. In order to provide meaningful hints to the user (by highlighting the conflicting form elemeents), i need to return more complex objects than just a string.

Is there a way to achieve this with validatejs? If yes, how?

As you can see in the snippet below, the validation method returns an object, which contains a message and the indices of begin and end. Using that, i wanted to highlight the corresponding form fields in the form.

// begin and end are both elements in an array. And i, j are the indices which refer to base/cmp in that array. 
// base.begin, base.end, cmp.begin and cmp.end are all moment.js objects.
if (base.begin.isAfter(cmp.begin)) {
    // if base.start is after cmp.start, then
    // base.begin has to be after cmp.end, too.
    var cmpEndsBeforeBase = base.begin.isAfter(cmp.end);
    if (!cmpEndsBeforeBase) {
        return {
            "message": cmp.title + " (" + cmp.end.format('YYYY MM DD') + ") ends after " + base.title + " starts (" + base.end.format('YYYY MM DD') + ")",
            "index": [i, j]
        }
    }
}
helt commented 9 years ago

to be more precise: I think, there is missing some information in the validate section of the documentation (http://validatejs.org/#validate).

helt commented 9 years ago

nevermind. http://validatejs.org/#custom-validator is giving the details, that the message can only be string or list of strings.

ansman commented 9 years ago

Does a list of strings solve your use case or do you require a new feature?

On Wed, Jul 8, 2015 at 1:28 PM, helt notifications@github.com wrote:

to be more precise: I think, there is missing some information in the validate section of the documentation (http://validatejs.org/#validate).

Reply to this email directly or view it on GitHub: https://github.com/ansman/validate.js/issues/62#issuecomment-119545795

helt commented 9 years ago

Of course, i can do some JSON.stringify and JSON.parse to mask the objects as arrays, but i do not really like that... Feels like a (awkward) workaround to me...

ansman commented 9 years ago

Do you have a concrete example so I understand the issue better?

I've been thinking that you should perhaps be able to return non strings and let the consumer of the errors handle it differently.