jwaliszko / ExpressiveAnnotations

Annotation-based conditional validation library.
MIT License
351 stars 123 forks source link

Overriding the default parser without the ValueParser annotation #79

Closed danieloprado closed 9 years ago

danieloprado commented 9 years ago

I've just noticed that I cant override the default validator parser when I dont provide an ValueParser annotation in my view model.

In that way I was unable to replace globally the default behavior.

In this PR I am providing a solution where when the annotation is not provided I try to fallback to the view model property type. So when I have a datetime without the annotation, I try to find a custom parser that matches the "datetime" name.

jwaliszko commented 9 years ago

Thank you for your contribution. I'll be able to review and test it within the next 2 weeks because If have no access to Visual Studio and all that stuff like computer right now. I you find some spare time try to present a code samples which help me to reproduce that issue. Otherwise it may be problematic. Thanks for understanding. Regards.

caferrari commented 9 years ago

We have a system where we have 100+ datetime fields and we live in Brasil "dd/mm/yyyy". Instead of put the ValueParser in all of the fields we did this one line change where the javascript checks if exists a custom parser in the system for the input. =)

It`s working flawless =)

// Date parser
ea.addValueParser('datetime', function (value) {
  if (/\/Date\(.+\)\//.test(value)) {
    return moment(value).toDate();
  }

  var date = moment(value, gorilla.formats.dateTime.dateAndHoursSeconds);
  if (date.isValid()) {
    return date.toDate();
  }
  return Date.parse(value) || value;
});

// Money parser
ea.addValueParser('numeric', function (value) {
  return globalize.parseFloat(value);
});
jwaliszko commented 9 years ago

Thanks, this solution is nice and simple.

Previously I've been thinking about adding new type-specific value parsers able to recognize all .NET types (next to already existing field-specific value parsers), e.g.

ea.addTypeParser('@typeof(DateTime).ToString() @typeof(DateTime?).ToString()', function(value) {
    ...
}

(I had even working implementation of that) but after a while I started to consider it overcomplicated.

One thing I've been slightly worried about was, that people will unintentionally register value parser under the name of some type, and will have globally parsed values for all fields of such a type, instead of for particular, attribute-decorated field only. Due to that I have done minor refactor https://github.com/JaroslawWaliszko/ExpressiveAnnotations/commit/8a80d46d3f25db376bd4cca1d052336047fdd7f0, and, among others, in the debug mode added a warning to the web console for these cases.