lukejagodzinski / meteor-astronomy-validators

https://atmospherejs.com/jagi/astronomy-validators
MIT License
11 stars 13 forks source link

How to display validation errors in the context of an Astronomy Model? #19

Closed tsega closed 8 years ago

tsega commented 8 years ago

In the documentation, I have seen that in order to display errors you are using an Astronomy model:

{{#with post}}
<input type="text" name="title" />
<div class="error">{{getValidationError "title"}}</div>
{{/with}}

My particular need is to know how to provide a User Astronomy model to my New User form in such a way that it will be empty of any validation errors when the form loads and would reactively display the errors when the model is validated?

I am able to do exactly what I've described above with the use of an extra Session variable but if feels "hacky"! I want to know how to do it properly.

Thanks for the amazing packages! :+1:

lukejagodzinski commented 8 years ago

You can do it in several ways. The one I've propose in the example app was here https://github.com/jagi/meteor-astronomy-examples/blob/master/client/routing.js#L31. However it's using routing. The better way for doing it would be using the onCreated hook of the template. One of the astronomy users posted such code, which seems to be very elegant way of doing it. It can look like this:

Template.InsertForm.onCreated(function() {
  this.user = new User();
});

Template.InsertForm.events({
  'change input': function(e) {
    var fieldValue = e.currentTarget.value;
    var fieldName = e.currentTarget.id;
    this.user.set(fieldName, fieldValue);
  }
});

And in template

<div>{{user.getValidationError 'fieldName'}}</div>

or

{{#with user}}
<div>{{getValidationError 'fieldName'}}</div>
{{/with}}
tsega commented 8 years ago

@jagi thanks for the quick reply, I tried the alternative you suggested but it didn't work for me so I went with the router option and now it works perfectly. The other thing I was looking for was to add custom messages to the validators that don't take a first argument, e.g. Validators.required(). Just tried Validators.required(null, "My Custom message") and it worked just fine.

I wanted to suggest that that should be in the documentation as well. Thanks again for your help!

lukejagodzinski commented 8 years ago

Ok no problem :-). Yes I'm working on documentation to make it's more detailed. There will be separate website with docs only, similar to Meteor docs.