简体   繁体   中英

Angularjs and displaying server validation message + Form builders

I am using Express + sequelizejs on the server side.

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 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:

{"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.

Since there are no models in Angular, the user in $parent.user.lastName is just a dumb Javascript object.

How can I get a validation message to attach to $parent.user.lastName and display it on the frontend?

The code above have some problems:

  • If the form is submitted as an empty form, then $parent.user is undefined
  • If a field is left empty, then $parent.user.fieldinquestion is undefined

Ultimately I want to make the code dry like helpers offered by plataformatec/simple_form

Is there such a library in Angular? Or do I sorta have to roll my own using Angular directives?

Thanks

Kind of working on something like this for our .Net apps. https://github.com/Envoc/envoc.directives/tree/master/src/validation

See the examples folder of that repo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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