angularvmware-clarityclarity

How to trigger Clarity form validation without simulating focus events?


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..


Solution

  • 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 {
                // ...
            }
        }
    }