Concise Form Validator In Vanilla JavaScript – formvalidatorjs

Category: Form , Javascript | October 12, 2018
Author: LukePeters
Views Total: 109
Official Page: Go to website
Last Update: October 12, 2018
License: MIT

Preview:

Concise Form Validator In Vanilla JavaScript – formvalidatorjs

Description:

formvalidatorjs is a lightweight, unobtrusive form validator written in vanilla JavaScript that works with the native HTML5 data validation.

How to use it:

Insert the JavaScript file validator-standalone.js into your webpage.

<script src="validator-standalone.js"></script>

Specify the custom error messages in the data-error-text attribute:

<form name="myForm" autocomplete="off" novalidate>

  <div class="form-input-wrap">
    <label for="myInput1">Text Field (not required)</label>
    <input type="text" name="myInput1" id="myInput" class="input" />
  </div>
  
  <div class="form-input-wrap">
    <label for="myInput2">Text Field (required, no error text)</label>
    <input type="text" name="myInput2" id="myInput2" class="input" required />
  </div>

  <div class="form-input-wrap">
    <label for="myInput3">Text Field (required, error text)</label>
    <input type="text" name="myInput3" id="myInput3" class="input" data-error-text="Error text custom to this field" required />
  </div>

  <div class="form-input-wrap">
    <label for="myInput4">Email Field</label>
    <input type="email" name="myInput4" id="myInput4" class="input" data-error-text="Please enter a valid email address" required />
  </div>

  <div class="form-input-wrap form-input-wrap--select">
    <label for="myInput5">Select Field</label>
    <select name="myInput5" id="myInput5" class="input" data-error-text="Please select an option" required>
      <option value="">Choose an option</option>
      <option value="Option 1">Option 1</option>
      <option value="Option 2">Option 2</option>
      <option value="Option 3">Option 3</option>
      <option value="Option 4">Option 4</option>
      <option value="Option 5">Option 5</option>
    </select>
  </div>

  <div class="centered">
    <input type="submit" value="Submit" class="button" />
  </div>

</form>

Initialize the form validatior and validate the form fields on submit.

const myForm = document.querySelector("form[name=myForm]");

myForm.addEventListener("submit", function(event) {

  if(validator.checkForm(event.target)) {
    alert("Continue processing the form!");
  }

  event.preventDefault();
});

Default settings.

{
  errored_input_classname: "errored",
  error_text_classname: "input-error",
  error_text_data_attribute: "data-error-text"
}

Leave a Reply