首页 文章

使用Ember Data处理服务器端验证

提问于
浏览
4

我在使用Ember和Ember Data处理服务器端验证时遇到问题 .

当发生验证错误时,API返回代码422.Ember数据然后触发模型上的 becameInvalid 回调 .

从这里开始,我不确定处理我遇到的错误的最佳方法是什么,以及如何让它们冒泡到视图中 .

App.Challenge = DS.Model.extend Ember.Validations,
    title: attr('string')
    summary: attr('string')
    # other attributes

    becameInvalid: (errors) ->
        # is it the place where I should handle the errors?
        # how would I make the errors bubble up to the view here?

我有2个问题 .

  • 我不确定 becameInvalid 是否是处理错误的地方,如果是,如何在视图中显示错误

  • becameInvalid 中, @get('isValid') 返回 true ,这对我没有意义 .

1 回答

  • 2

    这是我应该处理错误的地方吗?

    是 . 但你可能根本不需要做任何事情 . Ember-data希望你的api在其json响应中包含任何验证错误 . 该errors对象传递给 becameInvalid 钩子,并在模型上保存为属性 errors . 因此,如果您只想在视图中显示错误,那么执行以下操作可能就足够了:

    {{input value=firstName}}<p class="inline-help">{{errors.firstName}}</p>
    

    见:https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L50-L61

    在BecomeInvalid中,@ get('isValid')返回true,这对我没有意义

    同意这很奇怪 . 我认为这是一个绑定的东西,就像在绑定更新之前运行的BecomeInvalid钩子一样 .

相关问题