0

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 class="g-input form-control" 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.

2

1 Answer 1

1

.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 class="g-input form-control" 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.