New idea to perform EmberJS form validation (with Ember-Data)


#1

Hi everyone,

I’d like to share a new way of performing form validation using EmberJS and Ember-Data. Maybe this idea is not new, but I couldn’t find any library that implemented it this way, and I was not satisfied by the current solutions that mostly implied tying the validation rules into the model, which I don’t like.

Disclaimer: I’m still a beginner in JS, and I really struggle about how to organize reusable libraries, so for now the simplest way is to go to the code and copy-paste it: https://github.com/maestrooo/ember-html5-validation

The whole library is around 150 lines (without comments). The idea is that HTML5 gives us all the tools to perform basic validation on the client (any complex validation should be perform in the server anyway), so why not reuse this instead of writing custom validators in JS? Of course, this also means that it’s only support modern browsers and IE10+ (more on that later).

Here is a sample code:

{{#validatable-form classNames='register-form' action='register'}}
    <label for="first-name">First name</label>
    {{input id='first-name' autofocus='autofocus' required='required' value=firstName}}

    <label for="last-name">Last name</label>
    {{input id='last-name' required='required' value=lastName}}
{{/validatable-form}}

When an input looses focus, I actually only rely on HTML5 own validations (for required, type checking, min, max, step…). If you need more complex validations, pattern is actually awesome and, most of all, it’s defined in the spec that the validation message can be defined in the “title” attribute, so this library actually allows you to define custom validation quite easily.

It also supports Ember-Data out-of-the box through the DS.InvalidErrors object.

Regarding IE9 and lower, the idea is: I don’t care if I can provide them errors from the server. The current problem is that the whole code is tied with calls to the HTML5 validation, but it should be pretty easy to detect if HTML5 constraints API is supported, and if not, only waiting for server-side errors.

What do you think of the idea? Once again, I’m not sure this is an approach for all cases, but in my current application, it works actually pretty well!