AngularJS handle express-validation error like a pro

14 days ago

In this post I will show you how to handle form validation with express in the backend angularJS for front-end and handlebars for template engine.

api server
register.js

const { check, validationResult } = require("express-validator/check");
const userMdl = require("../../db/mdl_user");
const { logger } = require("../../lib/logger");

const register = async function (req, res) {
  console.log(req.body);
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    logger.error("vadidation error");
    return res.status(400).json({
      success: false,
      errors: errors.array(),
    });
  }
  const data = req.body;
  res.send(data);
};

module.exports = [
  check("name").trim().isLength({ min: 2 }),
  check("email")
    .isEmail()
    .custom((value) => {
      return userMdl.findOne({ email: value }).then((data) => {
        if (data) {
          return Promise.reject("E-mail này đã được tồn tại!");
        }
      });
    }),
  check("password").isLength({ min: 5 }),
  check("confirm_password").custom((value, { req }) => {
    if (value !== req.body.password) {
      throw new Error("Xác nhận mật khẩu không giống với mật khẩu!");
    }
    return true;
  }),
  register,
];

Handlebars

<div class="container">
  <div class="row">
    <div class="col-md-4 col-md-offset-3">
      <br />
      <div ng-controller="registerCtr" class="content-login">
        <h1>Đăng Ký Tài Khoản</h1>
        <div class="alert-danger" id="register-error"></div>
        <div class="alert-success" id="register-success"></div>

        <form ng-submit="submit(data)">
          <div class="form-group">
            <label for="email">Họ Tên:</label>
            <input
              type="text"
              class="form-control"
              required="required"
              name="name"
              placeholder="Nguyễn Văn A"
              ng-model="data.name"
            />
            <div class="alert-danger" ng-if="nameError">[{nameError.msg}]</div>
          </div>

          <div class="form-group">
            <label for="email">Email:</label>
            <input
              type="email"
              class="form-control"
              required="required"
              placeholder="vana@gmail.com"
              name="email"
              ng-model="data.email"
            />
            <div class="alert-danger" ng-if="emailError">[{emailError.msg}]</div>

          </div>
          <div class="form-group">
            <label for="password">Mật Khẩu:</label>
            <input
              type="password"
              class="form-control"
              required="required"
              minlength="6"
              name="password"
              ng-model="data.password"
            />
            <div class="alert-danger" ng-if="passwordError">[{passwordError.msg}]</div>
          </div>
          <div class="form-group">
            <label for="re_password">Xác Nhận Mật Khẩu:</label>
            <input
              type="password"
              class="form-control"
              required="required"
              name="confirm_password"
              ng-model="data.confirm_password"
            />
            <div class="alert-danger" ng-if="cpError">[{cpError.msg}]</div>
          </div>
          <button type="submit" class="btn btn-default">Submit</button>

        </form>
      </div>
    </div>
  </div>
</div>


angularjs controller

app.controller("registerCtr", [
  "$scope",
  "$http",
  function ($scope, $http) {
    console.log("AngularJS controller works....");
    $scope.data = {
      name: "xxx",
      email: "kinny@tranvuong.com",
      password: "password",
      confirm_password: "password",
    };
    $scope.submit = function (data) {
      console.log(data);
      $scope.loaded = true;
      $scope.error = false;
      $http
        .post("/register", data)
        .then(function (res) {
          console.log("success", res);
          $scope.loaded = false;
          if (!res.data) {
            $scope.error = true;
            $scope.errorMessage = "Something went wrong!";
          }
          $scope.entries = res.data;
        })
        .catch((err) => {
          console.log(err);
          $scope.nameError = err.data.errors.find((o) => o.param === "name");
          $scope.emailError = err.data.errors.find((o) => o.param === "email");
          console.log($scope.emailError, "emailerror");
          $scope.passwordError = err.data.errors.find(
            (o) => o.param === "password"
          );
          $scope.cpError = err.data.errors.find(
            (o) => o.param === "confirm_password"
          );
          $scope.loaded = false;
          $scope.error = true;
          $scope.errors = err.data.errors;
        });
    };
  },
]);