Home > Back-end >  Angular, Disable button validator
Angular, Disable button validator

Time:04-21

I hope you have a great day.

I'm getting stuck within creating a validator funciton. I want to disable a button if the text area is empty or if it contains "\n\n/Admin".

What I have done now is :

.html file

    <textarea  formControlName="messageBody" id="messageBody" tabindex="0" rows="4">
    </textarea>

    <button data-color="purple" type="submit" [disabled]="">
      <div>Send</div>
    </button>

.ts file

  initForm() {
this.form = this.fb.group({
  messageBody: [`\n\n/admin`, Validators.required, ]
});

I would really apprecaite if someone could help. Have a wounderful day.

CodePudding user response:

.ts file should be like below

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  form: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.initForm();
  }
  initForm() {
    this.form = this.fb.group({
      messageBody: [`\n\n/Admin`,[Validators.required,this.validateMessageBody()]],
    });
  }

  validateMessageBody(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      if(control.value){
        if(control.value.search('\n\n/Admin') !==-1){
          return { invalidMessageBody: { value: control.value }};
        }
        return null;
      }
      return null;
    };
  }
  get messageBody() {
    return this.form.get('messageBody');
  }
}

.html file should be like below

<form [formGroup]="form">
<textarea  formControlName="messageBody" id="messageBody" tabindex="0" rows="4">
</textarea>
<button data-color="purple" type="submit" [disabled]="messageBody?.errors?.required || messageBody?.errors?.invalidMessageBody">
  <div>Send</div>
</button>

</form>

View demo https://angular-ivy-cijsfx.stackblitz.io

  • Related