简体   繁体   English

AngularJS和显示服务器验证消息+表单构建器

[英]Angularjs and displaying server validation message + Form builders

I am using Express + sequelizejs on the server side. 我在服务器端使用Express + sequelizejs。

Assume we have the following view: (This is included as <div ng-include src="'views/users/_form.html'"></div> in the new, edit view.) 假设我们有以下视图:(在新的编辑视图中,它作为<div ng-include src="'views/users/_form.html'"></div>包含在内。)

<div class="form-group">
  <label for="userLastName">Last Name</label>
  <input type="text" class="form-control" id="userLastName" name="lastName" placeholder="Last name" ng-model="$parent.user.lastName">
   <!-- how to display a server validation message here? -->
</div>

And the following controller code that is responsible to create the user. 以及以下负责创建用户的控制器代码。

User.create($scope.user).$promise
  .then(function () {
    $location.path('/users')
    $scope.users = rePlanApi.User.query()
  })
  .catch(function (err) {
    _.forEach(err.data, function (errors, key) {
      if (key !== '__raw' && _.isArray(errors)) {
        _.forEach(errors, function (e) {
          $scope.user[key].$dirty = true
          $scope.user[key].$setValidity(e, false)
        })
      }
    })
  })

The server will return a 422 on validation error and a sample response could be: 服务器将针对验证错误返回422,并且示例响应可能为:

{"lastName":["Lastname does not fullfill a certain requirement", "Something else"]}

I understand I can use Angular can do certain validations, but there are things only a server can validate, like uniqueness of emails, etc. 我知道我可以使用Angular进行某些验证,但是有些事情只有服务器可以验证,例如电子邮件的唯一性等。

Since there are no models in Angular, the user in $parent.user.lastName is just a dumb Javascript object. 由于Angular中没有models ,因此$parent.user.lastName的用户只是一个愚蠢的Javascript对象。

How can I get a validation message to attach to $parent.user.lastName and display it on the frontend? 如何获取验证消息以附加到$parent.user.lastName并将其显示在前端?

The code above have some problems: 上面的代码有一些问题:

  • If the form is submitted as an empty form, then $parent.user is undefined 如果表单提交为空表单,则$ parent.user是未定义的
  • If a field is left empty, then $parent.user.fieldinquestion is undefined 如果字段为空,则$ parent.user.fieldinquestion未定义

Ultimately I want to make the code dry like helpers offered by plataformatec/simple_form 最终,我想像plataformatec/simple_form提供的助手一样使代码干燥

Is there such a library in Angular? Angular中有这样的图书馆吗? Or do I sorta have to roll my own using Angular directives? 还是我必须使用Angular指令来滚动自己的目录?

Thanks 谢谢

Kind of working on something like this for our .Net apps. 有点为我们的.Net应用程序做类似的事情。 https://github.com/Envoc/envoc.directives/tree/master/src/validation https://github.com/Envoc/envoc.directives/tree/master/src/validation

See the examples folder of that repo. 请参阅该仓库的示例文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM