On the server side, I am utilizing Express along with sequelizejs.
Let's say we have this particular view: (It 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>
As well as the following controller code that is tasked with creating 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)
})
}
})
})
In case of a validation error, the server will return a 422 status code and a sample response might look like:
{"lastName":["Lastname fails to meet a certain requirement", "Something else"]}
While Angular can handle some validations, certain checks such as uniqueness of emails require server-side validation.
Since Angular does not have models, the user in $parent.user.lastName
is simply a basic Javascript object.
How can I attach a validation message to $parent.user.lastName
and present it on the frontend?
The mentioned code has a few issues:
- If the form is submitted empty, then $parent.user is undefined
- If a field is left blank, then $parent.user.fieldinquestion is undefined
My ultimate goal is to streamline the code similar to what is offered by plataformatec/simple_form
Is there a library in Angular that provides a similar helper functionality? Or do I need to create my own using Angular directives?
Thank you