Home > Net >  Validation on <textarea> of html on click event of "add" button in Angular
Validation on <textarea> of html on click event of "add" button in Angular

Time:01-30

I'm working on Angular application.

I have one & "Add" Button.

Now how can I implement functionality that can do: if there is not a single value in then if I hit Add button I should get an error. That error has to mentioned as "Please add something in textarea". If User has already added then Success.

Can please some help?

I have tried onSubmit() form but not working

CodePudding user response:

In your typescript file, follow below steps

  1. Define FormGroup
addForm:FormGroup;
  1. Inject the FormBuilder Service in the constructor
constructor(private _formBuilder: FormBuilder){}
  1. Build Form in the ngOnInit Lifecycle
this.addForm = this._formBuilder.group({
    message: ['', [Validators.required]],
});

Now In your HTML file, use below code.

 <form [formGroup]="addForm">
    <mat-form-field [floatLabel]="'always'">
        <mat-label>Message</mat-label>
        <textarea matInput [rows]="3" [formControlName]="'message'"></textarea>
        <mat-error *ngIf="addForm.get('message').hasError('required')">
            Message is required.
        </mat-error>
    </mat-form-field>

    <button mat-flat-button [color]="'primary'" (click)="save()" [disabled]="addForm.invalid">
        <span>Save</span>
    </button>
</form>

If you want to disable until form validity then you can use invalid property of FormGroup as like I did.

Let me know if you've any queries. Happy Learning. ✌️

CodePudding user response:

    If you don't want to use reactive forms:
    In your html:
    <textarea [(ngModel)]="textArea"></textarea>
    <button (click)="onSubmit()">Submit</button>
    In your ts:
      onSubmit() {
        console.log(this.textArea);
    if(this.textArea!=undefined){
        this.textArea = this.textArea.replace(/\s/g, '');
    }
        if (
          this.textArea == undefined ||
          this.textArea == '' ||
          this.textArea == null
        ) {
          alert('Please enter the data in text area!');
        } else {
          alert('data entered successfully');
        }
      }
    
    Use the following stackblitz link for reference: 

https://stackblitz.com/edit/angular-bx2xjc
  • Related