Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 validation date field using form builder

Tags:

i have form and i want to validate date field on submit, i am using Form Builder, how can i do this(the angular way) ? another problem why i cant see the value published_date in the date field ? i tried to search and i can't find solution for input date field.

unamePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
  ngOnInit() {
    this.book = 
      {
        id: 55,
        author_name : "vv",
        published_date :  new Date('01/02/2018'),
        title : "cc"
      };
      
      this.form = this.formBuilder.group({
        title : ['', Validators.required],
        author : ['', Validators.required],
        datePublish: ['', Validators.pattern(this.unamePattern)],
        }
      );
  }
<input 
            [(ngModel)]="book.published_date"
            id="dateOfBirth" 
            class="form-control" 
            placeholder="yyyy-mm-dd" 
            name="dp" 
            ngbDatepicker 
            formControlName="datePublish"
            #dp="ngbDatepicker">
            
          <div class="input-group-append">
            <button class="btn btn-outline-secondary" (click)="dp.toggle()" type="button">
                <i class="fa fa-calendar" aria-hidden="true"></i>
            </button>
          </div>
like image 971
Asaf shay Avatar asked Jul 05 '18 07:07

Asaf shay


2 Answers

If you could use momemt() then it will very easy to get hands on date time things and you could write your own validator as

import {AbstractControl} from '@angular/forms';
import * as moment from 'moment';

export class YourValidator {
  static dateVaidator(AC: AbstractControl) {
    if (AC && AC.value && !moment(AC.value, 'YYYY-MM-DD',true).isValid()) {
      return {'dateVaidator': true};
    }
    return null;
  }
}

And in your form object you could use it like

import {YourValidator} from "....";

this.form = this.formBuilder.group({
    title : ['', Validators.required],
    author : ['', Validators.required],
    datePublish: ['', Validators.compose([Validators.required, YourValidator.dateVaidator])],
});

Demo stackblitz.com/angular-date-validator

like image 114
M Khalid Junaid Avatar answered Oct 12 '22 11:10

M Khalid Junaid


For date validation you can use ng4-validators.

npm i ng4-validators --save

Import and use:

import { CustomValidators } from 'ng4-validators';

ngOnInit() {
  this.book = 
    {
      id: 55,
      author_name : "vv",
      published_date :  new Date('01/02/2018'),
      title : "cc"
    };

    this.form = this.formBuilder.group({
      title : ['', Validators.required],
      author : ['', Validators.required],
      datePublish: ['', CustomValidators.date,
      }
    );
  }
like image 42
Benjamin Taylor Avatar answered Oct 12 '22 11:10

Benjamin Taylor