How to trigger Clarity form validation without simulating focus events?

1.2k Views Asked by At

How can I trigger the validation of the new Clarity 0.13 forms? I'm using reactive forms and I want to trigger the validation without actually focusing/unfocusing the inputs. This will be necessary in my application when a user hits "Save" before completing the form. Currently I can't think of a way to trigger the Clarity error state without triggering actual blur events on the DOM elements which seems way to complicated for such a simple task.

Here is a stackblitz where you can reproduce the problem: https://stackblitz.com/edit/clarity-light-theme-v013-6s2qtq

Naturally nothing happens when clicking "Validate Form" because I don't know what to call in the function..

2

There are 2 best solutions below

1
On BEST ANSWER

The newest version supports marking clarity forms as dirty - citing the docs:

import {ViewChild, Component} from "@angular/core";
import {FormGroup, FormControl, Validators} from "@angular/forms";

@Component({
    template: `
    <form clrForm [formGroup]="exampleForm">
        <input clrInput formControlName="sample" />
        <button class="btn btn-primary" type="submit" (click)="submit()">Submit</button>
    </form>
    `
})
export class ReactiveFormsDemo {
    @ViewChild(ClrForm) clrForm;

    exampleForm = new FormGroup({
        sample: new FormControl('', Validators.required),
    });

    submit() {
        if (this.exampleForm.invalid) {
            this.clrForm.markAsDirty();
        } else {
            // ...
        }
    }
}
1
On
import { Component, OnInit,Input } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  styleUrls: ['app.component.css'],
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {

  @Input() awesomeForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {

    this.awesomeForm = this.fb.group({
      awesome: ['', Validators.required]
    })  
   this.awesomeForm.valueChanges.subscribe(changes => {
    // do what you need with the form fields here
    // you can access a form field via changes.fieldName
    this.validateForm(changes);
    });
  }
  public resetForm() {
    this.awesomeForm.reset();
    console.log('Error state is still active. :(');
  }

  public validateForm(changes: any) {
    console.log('How to trigger validation without hacking focus events on the dom element?');
    console.log('triggered and got changes',changes)
  }

}

You can subscribe to FormGroup object valueChanges observable and this has all the fields present on your form , once you get the field values you can basically trigger your validation function on each field change method and pass it on the validateForm(changes:any)