DEV Community 👩‍💻👨‍💻

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Updated on

TIL: How to add validation on Agular Material form field

I'm using a text area inside a form field from Angular Material components. My view for postMessage component looks something like this:

post-message.component.html

<form class="post-message-form">
    <mat-form-field class="full-width">
     <textarea matInput [formControl]="messageFormControl" 
            cdkTextareaAutosize cdkAutosizeMinRows="1" 
            maxlength="500" placeholder="What's happening?"> 
     </textarea>
     <mat-error 
         *ngIf="messageFormControl.hasError('required')">
           Message is <strong>required</strong>
     </mat-error>
    </mat-form-field>
<form>  
Enter fullscreen mode Exit fullscreen mode

And on my controller, I initialize the form control with an empty value

post-message.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'post-activity',
  templateUrl: './post-activity.component.html',
})
export class PostActivityComponent implements OnInit {
  messageFormControl = new FormControl('' 
     [Validators.required]);

  constructor() { }

  ngOnInit(): void {
    //other code
  } 
}
Enter fullscreen mode Exit fullscreen mode

Here, I have declared a form control as messageFormControl and added a built-in required validation. The form control takes validation as an array; so for example, if I want to add an email validation then it will look something like

messageFormControl = new FormControl('' 
     [Validators.required, Validators.email]);
Enter fullscreen mode Exit fullscreen mode

You can also add your own custom validation on the array but might create a separate post for that.

That's all for today.

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.