Home > Software engineering >  Angular material reactive forms validation
Angular material reactive forms validation

Time:11-26

I want to use form validators, but I don't exactly know how, I'm trying to set a validation of max-length and required at the same time, but I am not able to, also I had looked for it and found nothing

Here us what I tried to do:

import { literalMap } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
// import {FormsModule, ReactiveFormsModule} from '@angular/forms'
// import { FormControl } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  profileForm = new FormGroup({
    firstName: new FormControl('',Validators.maxLength(1), Validators.required),
    email: new FormControl('',Validators.email),
  });
  constructor() { }

  ngOnInit(): void {
  }
  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.profileForm.value);
  }
  testForm(){
    let a = this.profileForm.get('email').valid
    if (a){
      alert('jalo')
    }
  }
  save(){
    let email = this.profileForm.get('email').value
    if(email != '' ){
      alert('jalo')
    }
  }

}

CodePudding user response:

put the two Validators in the table like that

 profileForm = new FormGroup({
    firstName: new FormControl('',[Validators.maxLength(1), Validators.required] ),
    email: new FormControl('',Validators.email),
  });
  • Related