Unlock Angular Form Validation Magic with Trivule: The Game-Changing Approach

claudye

Claude Fassinou

Posted on May 7, 2024

Unlock Angular Form Validation Magic with Trivule: The Game-Changing Approach

If you're aiming to save time, minimize effort, yet achieve sophisticated form validation in your Angular projects, this article is for you. Form validation in Angular can sometimes be complex, especially when managing error messages, dealing with multiple if-else conditions, handling button states, and styling invalid inputs. But fear not! With this method, you won't need to write any conditions at all. Yes, you read that right. Just a simple configuration, and you're good to go.

To achieve this, I'll introduce you to a well-thought-out library designed to streamline form handling, saving you time and effort: Trivule

Install Trivule in Your Angular Projects

npm install trivule
Enter fullscreen mode Exit fullscreen mode

Create Your Angular Component

ng g c contact-form
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to Your Component TypeScript and HTML Files
    • HTML Template
<div #signupForm class="form">
    <p>Validation scenario with Trivule</p>
    <fieldset>
        <label>
            File
            <!--Required file, with mimes type .png-->
            <input name="file" type="file" data-tr-rules="required|mimes:.png" />
            <div data-tr-feedback="file"></div>
        </label>
        <label>
            Email
            <input type="email" name="email" data-tr-rules="required|email" />
            <div data-tr-feedback="email"></div>
        </label>
        <label>Your favorite language</label>
        <select name="favorite_cuisine" data-tr-rules="required">
            <option selected value="">Select ...</option>
            <option>JavaScript</option>
            <option>TypeScript</option>
            <option>HMTL</option>
        </select>
        <div data-tr-feedback="favorite_cuisine"></div>
    </fieldset>
    <input type="submit" value="Subscribe" data-tr-submit (click)="save()" />
</div>
Enter fullscreen mode Exit fullscreen mode
  • Component TypeScript
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { TrivuleForm } from 'trivule';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent implements AfterViewInit {
  @ViewChild('signupForm') signupForm!: ElementRef<HTMLElement>;

  trivuleForm: TrivuleForm | null = null;

  ngAfterViewInit(): void {
    if (this.signupForm?.nativeElement) {
      this.trivuleForm = new TrivuleForm(this.signupForm.nativeElement, {
        validClass: 'is-valid',//class to add when the valid passes
        invalidClass: 'is-invalid'//class to add when the valid fails
      });
      this.trivuleForm.init();
    }
  }
  save(): void {
    const formIsValid = this.trivuleForm?.passes(); // indicate if the validation passes
    const validatedInput = this.trivuleForm?.validated(true); //Get only validated input
    const allInputs = this.trivuleForm?.inputs(true); //Get all inputs
    const failedInputs = this.trivuleForm?.failed(true); //Get failed inputs
  }
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • @ViewChild('signupForm') signupForm!: ElementRef<HTMLElement>; selects the form or HTML element containing the inputs, in our case, the HTML element with the #signupForm attribute.
  • In the ngAfterViewInit method, we initialize a Trivule instance, passing it the HTML element. Then, the init method on trivuleForm proceeds with the validation as the user interacts with the form.
  • Attributes prefixed with data-tr are Trivule attributes that instruct the input on how to behave, where to display messages, and more.

Attribute Explanation:

  • data-tr-rules: Specifies validation rules.
  • data-tr-feedback: Indicates where an HTML element will display feedback.
  • data-tr-submit: Enables or disables the button based on form validity.

Learn More about Trivule
Trivule on Github

Trivule can also be used to manage Reactive Forms in Angular.
If you found this article helpful, share it and subscribe to my account for more insightful content.

💖 💪 🙅 🚩
claudye
Claude Fassinou

Posted on May 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related