DEV Community

Cover image for Best and Simple Real-Time Validation Library Without Needing JavaScript Code
Claude Fassinou
Claude Fassinou

Posted on

Best and Simple Real-Time Validation Library Without Needing JavaScript Code

Expected results

Image description

Validating a form in HTML and CSS can be challenging, but it becomes easier with Trivule. Learn by example how to use dynamic validation rules such as dateBefore, dateAfter, and dateBetween (alias between) to make date validation interactive and real-time. Learn more in this article or in the documentation of Trivule.

Step 1: HTML Element Configuration

Start by integrating a date field into your HTML form. Add the data-tr-rules and data-tr-messages attributes to define validation rules and custom error messages.

<div class="form">
  <label class="label">Your date of birth</label>
  <input
    type="date"
    data-tr-rules="required|dateBetween:1990-01-01 00:00,1999-12-31 23:00"
    data-tr-messages="Date of birth is required|You must be born between 1990 and 1999."
    name="birthDay"
  />
  <!-- Location to display error messages, can be any HTML element -->
  <div data-tr-feedback="birthDay"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 2: Including the Trivule Library

Add the Trivule script to your HTML page to enable form validation.

<script src="https://www.trivule.com/js/trivule.js"></script>
Enter fullscreen mode Exit fullscreen mode

Step 3: Trivule Initialization

Create an instance of TrivuleInput by specifying the selector of the element to validate (here, a date field) and call the init() method to activate validation.

<script>
  const trInput = new TrivuleInput("input[name=birthDay]");
  trInput.init();
</script>
Enter fullscreen mode Exit fullscreen mode

Step 4: Some Validation Rules on Dates

  • dateBefore:date: Validates that the date is before the specified date.

  • dateAfter:date: Validates that the date is after the specified date.

  • dateBetween:start,end or date|between:start,end: Validates that the date is between the two specified dates, inclusively.

Note: The between rule must be preceded by the date rule so that the between rule knows it will compare dates.

Conclusion

Date validation with Trivule offers a simple yet powerful solution to ensure users input valid dates in your forms. By using rules like dateBefore, dateAfter, and dateBetween, easily customize the validation behavior according to your specific needs. There are several other rules in Trivule; please consult them here.

Top comments (0)