Validate Form Fields Using Regex And Required Attribute – Coriander

Category: Form , Javascript | January 10, 2019
Author:brandnpatterson
Views Total:594 views
Official Page:Go to website
Last Update:January 10, 2019
License:MIT

Preview:

Validate Form Fields Using Regex And Required Attribute – Coriander

Description:

Coriander is a dead simple form validator used for validating form fields using Regex and required attribute.

You’re allowed to customize the error message displayed under the form fields when invalid.

How to use it:

Install & import the Coriander library.

# NPM
$ npm install coriander --save

Or from the CDN.

<script src="https://unpkg.com/coriander"></script>

Define your validation rules using the Regex.

<form class="form">
  <input
    class="form-input"
    type="text"
    id="email"
    name="email"
    data-error="Please enter a valid email"
    data-regex="^[a-zA-Z0-9]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"
    data-required="true"
  />
  <input
    class="form-input"
    type="tel"
    id="phone"
    name="phone"
    data-error="Please enter a 10 digit phone number"
    data-regex="^[2-9]{2}[0-9]{8}$"
    data-required="true"
  />
  ...
</form>

Attach the form validator to the HTML form.

const form = document.querySelector('.form');
coriander(form);

Decide whether to validate form fields when the values are changed.

coriander(form,{
  onChange: true
});

Execute a function on form submit.

coriander(form,{
  onSubmit(data) {
    // ...
  }
});

You Might Be Interested In:


Leave a Reply