How to validate this birthday form in sign up form in Angular?

1.7k Views Asked by At

I am trying to validate this birthday form?

HTML

  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
  <input type="text" class="form-control" id="usr" placeholder="Day">
</div>
    </div>
    <div class="col-md-4">
      <div class="form-group">
  <select class="form-control" id="sel1">
    <option value="" disabled selected>Month</option>
    <option>January</option>
    <option>February</option>
    <option>March</option>
  </select>
</div>
    </div>
     <div class="col-md-4">
      <div class="form-group">
  <input type="text" class="form-control" id="usr" placeholder="Year">
</div>
    </div>

TypeScript

ngOnInit() {
 this.SignupForm = new FormGroup({
       'username': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])'),
       ]),
       'name': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[a-z])(?=.*[A-Z])'),
       ]),
      'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails),
      'password': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}'),
       ]),
       'phone': new FormControl(null, [Validators.required,
      Validators.pattern('(?=.*[0-9])'),
       ]),
    });
}

I am using a reactive form builder to validate other fields like Username, password... I also found this question here where was suggested to use moment.js but was confused. Can't figure out how to use moment js with this form for validating above mentioned birthday field with the moment.

3

There are 3 best solutions below

3
On

You need to create a new form group for your birthday form, then you can validate each control: Day, Month, Year against a regular expression that ensures the combines value adheres to the format you desire (11/11/18) for example.

You don't need Moment.js unless you are trying to prepopulate a date, even then this isn't to do with validation, but rather the date it produces will need to be validated.

1
On

I read your comments and I believe you really do not want these to be select input. You should go with proper datepicker plugin with reactive form.

You should go through ng-bootstrap which provides ngbDatepicker which can help you in all the way you want - Validation and actual datepicker. It provides integration with reactive form.

Hope this helps.!

0
On

Check this answer that solves a similar problem:

Validate if age is over 18 years old with Angular Reactive Forms

It's quite detailed. Also, a working example is included. You can just ignore the last part if you don't need to check if people are over 18 years old.