This will show you how to handle form errors with Node.js and AngularJS when server-side validation is necessary. It highlights the erroneous field and displays an error message below indicating the problem. This example uses Node.js, Express, Express Validator, AngularJS and Bootstrap 3.
The form uses standard Bootstrap conventions, but with the addition of Angular, it comes alive. By using 'ng-class' the Bootstrap 'has-error' class will be applied if an error is thrown. In this case errors.fname
indicates there was an error with the fname
field. The help-block
will also appear in the event of an error.
<form class="form-horizontal" ng-submit="save_account()" data-ng-init="init()" ng-controller="AccountCtrl">
<div class="form-group" >
<label class="col-md-4 control-label" for="fname"></label>
<div class="col-xs-12" ng-class="{ 'has-error': errors.fname }">
<input id="fname" name="fname" ng-model="fname" type="text" placeholder="First Name" class="form-control input-md" value="{{fname}}" required="">
<p class="help-block" ng-model="errors.fname" ng-show="errors.fname">Please enter your First name.</p>
</div>
</div>
</form>
This is the server-side code that handles the data passed by Angular. We're using Express Validator which creates a JSON object using param
and msg
to indicate the field and problem respectively. In this example the msg
value is ignored in place of the inline error message on the form.
app.post('/save/account', function(req, res) {
req.assert('fname').notEmpty();
var errors = req.validationErrors();
if(errors) {
res.json(500, errors);
return;
}
}
This is the controller that handles the form submission and validation. I've excluded the success code since the focus here is error handling. All this really does is pulls apart the Express Validator object and creates an errors
object. AngularJS will automatically update the form based on this.
$scope.save_account = function() {
$http.post('/save/account', { fname: $scope.fname })
.success(function(data, status, headers, config) {
// Good to go!
}
.error(function(data, status, headers, config) {
// Convert server side errors to AngularJS errors.
var errors = {};
for(var i = 0; i < data.length; i++) {
var err = data[i];
var param, msg;
for(var key in err) {
if(key == 'param') param = err[key];
if(key == 'msg') msg = err[key];
}
errors[param] = msg;
}
$scope.errors = errors;
});
}
And there you have it! A very simple and clean way to handle form errors with server validation.