Angular, Forms

Server side form validation with Angular and Nodejs

Spread the love

In this tutorial you will learn Angular reactive form validation with interact server side Nodejs express validation. Step by step follow the main bold points that key things and Github project link share in blow.

Angular side reactive form validation with server side error response

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule, 
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<form
  [formGroup]="registerForm"
  #ngForm="ngForm"
  (ngSubmit)="submitRegisterFrm()"
>
  <input
    type="text"
    formControlName="username"
    [class.is-invalid]="
      registerFrmCtrl.username.invalid &&
      (registerFrmCtrl.username.touched || ngForm.submitted)
    "
    placeholder="username"
  />
  <div
    *ngIf="
      registerFrmCtrl.username.invalid &&
      (registerFrmCtrl.username.touched ||
        registerFrmCtrl.username.dirty ||
        ngForm.submitted)
    "
  >
    <span *ngIf="registerFrmCtrl.username.errors?.required">
      First name is required</span
    >
    <span
      class="alphabet-error"
      *ngIf="registerFrmCtrl.username.errors?.pattern"
      >Only alphabets allowed</span
    >
    <span *ngIf="registerFrmCtrl.username.errors?.serverError">{{
      registerFrmCtrl.username.errors?.serverError
    }}</span>
  </div>
  <input
    type="text"
    formControlName="email"
    [class.is-invalid]="
      registerFrmCtrl.email.invalid &&
      (registerFrmCtrl.email.touched || ngForm.submitted)
    "
    placeholder="Email"
  />
  <div
    *ngIf="
      registerFrmCtrl.email.invalid &&
      (registerFrmCtrl.email.touched ||
        registerFrmCtrl.email.dirty ||
        ngForm.submitted)
    "
  >
    <span *ngIf="registerFrmCtrl.email.errors?.required">
      Email is required</span
    >
    <span *ngIf="registerFrmCtrl.email.errors?.serverError">{{
      registerFrmCtrl.username.errors?.serverError
    }}</span>
  </div>
  <input
    type="text"
    formControlName="password"
    [class.is-invalid]="
      registerFrmCtrl.password.invalid &&
      (registerFrmCtrl.password.touched || ngForm.submitted)
    "
    placeholder="Password"
  />
  <div
    *ngIf="
      registerFrmCtrl.password.invalid &&
      (registerFrmCtrl.password.touched ||
        registerFrmCtrl.password.dirty ||
        ngForm.submitted)
    "
  >
    <span *ngIf="registerFrmCtrl.password.errors?.required">
      Password is required</span
    >
    <span
      class="alphabet-error"
      *ngIf="registerFrmCtrl.password.errors?.pattern"
      >Only alphabets allowed</span
    >
    <span *ngIf="registerFrmCtrl.password.errors?.serverError">{{
      registerFrmCtrl.password.errors?.serverError
    }}</span>
  </div>
  <button type="submit">Submit</button>
</form>

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { HttpService } from './http.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'angular';
  form: FormGroup;
  constructor(private _fb: FormBuilder, private _httpService: HttpService) {
    this.form = this._fb.group({
      registerForm: this._fb.group({
        username: ['', [Validators.required]],
        email: ['', [Validators.required]],
        password: ['', [Validators.required]],
      }),
    });
  }

  get registerFrmCtrl() {
    return (<FormGroup>this.form.get('registerForm')).controls;
  }

  get registerForm() {
    return this.form.get('registerForm');
  }

  submitRegisterFrm() {
    this._httpService
      .register(
        'http://localhost:4200/api/users/register',
        this.registerForm.value
      )
      .subscribe(
        (result) => {},
        (err) => {
          if (err.status == 400) {
            console.log(err);
            const validationError = err.error.errors;
            Object.keys(validationError).forEach((index) => {
              const formControl = this.registerForm.get(
                validationError[index].param
              );
              if (formControl) {
                formControl.setErrors({
                  serverError: validationError[index].msg,
                });
              }
            });
          }
        }
      );
  }
}

Further search for Angular form

http.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class HttpService {
  constructor(private _http: HttpClient) {}
  register(route, data) {
    let httpHeaderValue = new HttpHeaders();
    httpHeaderValue = httpHeaderValue.set('Content-Type', 'application/json');
    return this._http.post(route, data).pipe(map((response: any) => response));
  }
}

Nodejs server side validation with angular request

We will use express-validator middlewares that validate

npm install --save express-validator

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/api/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

users.js

var express = require("express");
var router = express.Router();


router.post(
  "/register",
  body("username").custom((value) => {
    // Check with Database model method findUserByUserName
    /* return User.findUserByUserName(value).then(user => { */
    if (value == "username") {
      return Promise.reject("User name already in use");
    }
    return true;
    /*  }); */
  }),
  body("email").isEmail().normalizeEmail(),
  body("password").isLength({
    min: 6,
  }),
  (req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        errors: errors.array(),
      });
    }

    res.status(200).json({
      success: true,
      message: "Login successful",
    });
  }
);
module.exports = router;

Github links

Referances

Thank you! Please subscribe and share to get new interesting update articles.


Spread the love
Tagged ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

1 thought on “Server side form validation with Angular and Nodejs

Leave a Reply

Your email address will not be published.