Подтвердить, если возраст старше 19 лет - PullRequest
0 голосов
/ 15 февраля 2020

Я хочу показать сообщение, если пользователь вводит неверную дату рождения. Сообщение: "возраст должен быть> 19"

компонент. html

<form #userForm="ngForm">

    <input type="text" required class="form-control" name="name" [(ngModel)]="credentials.name" ngModel>

    <input type="email" required class="form-control" name="email" [(ngModel)]="credentials.email" ngModel>

    <input type="password" class="form-control" name="password" [(ngModel)]="credentials.password" ngModel>

    <input type="tel" required class="form-control" name="phone" [(ngModel)]="credentials.phone" ngModel>

    <input type="date" #birthDate="ngModel" required [class.is-invalid]="birthDate.invalid && birthDate.touched"
        class="form-control" name="birthDate" [(ngModel)]="credentials.birthDate" ngModel>
    <small class="text-danger" [class.d-none]="birthDate.valid || birthDate.untouched">Please
        enter your birth date</small>

    <div class="text-danger" *ngIf="isError"> age should be > 19 </div>

    <button type="button" class="btn btn-lg block">Register</button>

</form>

component.ts

@Component({
    templateUrl: "./register.component.html"
})

export interface TokenPayload {
    id: number
    name: string
    email: string
    phone: string
    password: string
    birthDate: string
}

export class RegisterComponent {
    constructor() {}

    credentials: TokenPayload = {
        id: 0,
        name: "",
        email: "",
        password: "",
        phone: "",
        birthDate: "",
    };
    ageError = false;
    age: number;
    today = new Date();
    bdate = new Date(this.credentials.birthDate); //<----- here no date store in bdate

    c_day = this.today.getDate();
    c_month = this.today.getMonth();
    c_year = this.today.getFullYear();

    b_day = this.bdate.getDate();
    b_month = this.bdate.getMonth();
    b_year = this.bdate.getFullYear();

    this.age = this.c_year - this.b_year;
    if (this.c_month < this.b_month - 1) {
        this.age--;
    }

    if (this.b_month - 1 === this.c_month && this.c_day < this.b_day) {
        this.age--;
    }
    if (this.age < 19) {
        this.ageError = true;
    }
}

В component.ts я объявляю интерфейс и в файле класса использую этот интерфейс.

Когда пользователь заполняет форму и вводит дату своего рождения, я хочу показать сообщение, если возраст меньше чем 19.

Но это не работает. Как мне сделать это правильно?

1 Ответ

0 голосов
/ 15 февраля 2020

1) Попробуйте использовать реактивную форму. Это облегчит проверку подтверждений в вашей форме

2) Если вы используете такой же подход, как вы можете проверить свой возраст при выборе какой-либо даты в dob

Проверьте ниже код. Я сделал это в вашем коде:

.ts файл

import { Component } from '@angular/core';

export interface TokenPayload {
  id: number
  name: string
  email: string
  phone: string
  password: string
  birthDate: string
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  credentials: TokenPayload = {
    id: 0,
    name: "",
    email: "",
    password: "",
    phone: "",
    birthDate: "",
  }
  ageError = false;
  age: number;
  today = new Date();
  bdate = new Date(this.credentials.birthDate);
  c_day = this.today.getDate();
  c_month = this.today.getMonth();
  c_year = this.today.getFullYear();

  b_day = this.bdate.getDate();
  b_month = this.bdate.getMonth();
  b_year = this.bdate.getFullYear();

  constructor() {
    this.age = this.c_year - this.b_year;
    if (this.c_month < this.b_month - 1) {
        this.age--;
    }
   }

   checkDate(){
     if(this.credentials.birthDate){
       let selectedDate =new Date(this.credentials.birthDate);
       let selectedYear = selectedDate.getFullYear();
       let ageDiff =  this.c_year - selectedYear
       if(ageDiff < 19){
         console.log(ageDiff)
         this.ageError = true
       }
     }
   }
}

. html файл

<form #userForm="ngForm"> 

        <input type="text" required class="form-control" name="name"
        [(ngModel)]="credentials.name" ngModel>

        <input type="email" required class="form-control" name="email" 
        [(ngModel)]="credentials.email" ngModel>

        <input type="password" class="form-control" name="password" 
        [(ngModel)]="credentials.password" ngModel>

        <input type="tel" required class="form-control" name="phone"
        [(ngModel)]="credentials.phone" ngModel>

        <input type="date" #birthDate="ngModel" required
        [class.is-invalid]="birthDate.invalid && birthDate.touched" class="form-control"
        name="birthDate" [(ngModel)]="credentials.birthDate"
        ngModel (input)="checkDate()">
       <small class="text-danger" [class.d-none]="birthDate.valid || birthDate.untouched">Please 
       enter your birth date</small>

       <div class="text-danger" *ngIf="ageError"> age should be > 19 </div>

    <button type="button" class="btn btn-lg block">Register</button>
  </form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...