Monday 1 April 2024

Custom Validator for Whitespace and Nextline in Textboxes in Angular

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, AbstractControl, ValidationErrors, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
 
  studentForm!: FormGroup;
 
  constructor(private formBuilder: FormBuilder){
   
  }
  ngOnInit(): void{
     this.studentForm = this.formBuilder.group({
        studentName: ['',[Validators.required, this.checkWhitespaceNextlineValidator()]],
        studentMarks: ['',[Validators.required, this.checkWhitespaceNextlineValidator()]]
     });
  }

  checkWhitespaceNextlineValidator(){
    return (control: AbstractControl): ValidationErrors | null => {
      const isNewline = control?.value?.replaceAll(/&lt;,*?&gt;/g, "")?.replaceAll(/<.*?>/g, "");
      const isWhitespace = (isNewline || '').trim().length === 0;
      return isWhitespace ? { whitespace: true } : null;
    }
  }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.