Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Dependencies

Vanilla JS - form validator

A pure Javascript validator form replace Jquery Validation.

It allows you to:

  • Validate input fields with pre-existing or custom rules
  • Retrieve validation errors
  • Display validation errors below unvalidated fields
  • Support multiple languages for error messages
  • Add validation errors under input not validated
    • To consider the language

Getting Started

Download the script file clicking here

Including in Your Project

Include the following in your HTML:

<linkhref="./src/style.css" rel="stylesheet"><formid="form-id"><inputtype="text" name="firstName" placeholder="First name"><inputtype="email" name="email" placeholder="john@doe.com"><textareaname="textarea" placeholder="Message" rows="10"></textarea><buttontype="submit" class="btn btn-primary">Send</button></form><scriptsrc="./src/app.js" type="module" async></script>

Creating an Instance

Create an instance of FormValidator and configure it as follows:

import{FormValidator}from"./modules/form-validator.js";classApp{constructor(){this.form=document.querySelector('#form-id');this.validator=newFormValidator({form: this.form,validationRules: {firstName: "required|match:/^[A-z]{1}[a-z]+$/",lastName: "required",email: 'required|email',textarea: 'required|min:2|max:5'},local: "fr",// Options: "en", "fr"observeOnInput: true});}init(){this.form.addEventListener('submit',(event)=>{event.preventDefault();this.validator.validate(event.target);if(this.validator.isValide()){constdata=this.validator.getData();console.log(data);console.log(JSON.stringify(data));// Send data to server}else{this.validator.setErrors();consterrors=this.validator.getErrors();console.log(errors);}});}}constmyApp=newApp();myApp.init();

Constructor Options

The FormValidator constructor accepts an options object with the following properties:

  • form: HTMLElement The form element to be validated. This is a required option.

  • validationRules: Object An object defining the validation rules for each form field. Each key corresponds to a field name, and the value is a string with validation rules separated by pipes (|). Supported rules include:

  • required: Field must not be empty

  • email: Field must be a valid email address

  • min:n: Field must have at least n characters

  • max:n: Field must have at most n characters

  • match:pattern: Field value must match the given regular expression pattern

    • local: String The language for error messages. Supported values are "en" for English and "fr" for French. You can add another language by modifying the local.js file in the modules folder.
    • en: English
    • fr: French
    • observeOnInput: Boolean If true, the validator will validate fields on input events. If false, it will only validate on submit events. Default is false.

Validation rules (required)

Validation rules are defined in the validationRules option, following this format:

validationRules : {fieldName : "ruleName|RuleName:option|RuleName:option|...",fieldName : "ruleName|ruleName|..."}

Available Validation Rules

Rule NameRule optionDescription
required-Ensures the field is not empty
email-Validates email forma
max:intinteger [number]Maximum length of characters
min:intinteger [number]Minimum length of characters
match:patternstring [patern]Costum rule validation

Validation rules exemple

validationRules : {firstName : "match:/^[A-z]{1}[a-z]+$/",// match:preg_matchemail : "required|email",// required and emailtextarea : "required|min:2|max:5"// required and min:2 character and max:5 characters...}

Methodes

Name: isValide

After a submit, the isValide() method returns true or false if error variable is empty or not.

validator.isValide()

Name: setErrors

After a submit, the setErrors() method displays the error messages below the unvalidated fields.

validaed fieldunvalidated field

Name: getErrors

After a submit the getErrors() method returns an object with each unvalidated field.

validator.getErrors(){{"firstName": {"required": "Please enter a message","match": "The value is not valid"},"email": {"required": "Please enter a message","email": "The email is not valid"},"textarea": {"required": "Please enter a message","min": "This field must contain at least 2 characters"}}}

Example of Form Integration

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible" content="IE=edge"><metaname="viewport" content="width=device-width, initial-scale=1.0"><title>Simple Form Validator</title><linkrel="stylesheet" href="./src/style.css"><scriptsrc="./src/app.js" type="module" async></script></head><body><formmethod="GET" action="#" class="form" id="form-id"><h1>JavaScript - Form Validator</h1><labelfor="firstName">First name</label><inputtype="text" name="firstName" id="firstName" placeholder="First name"><labelfor="lastName">Last name</label><inputtype="text" name="lastName" id="lastName" placeholder="Last name"><labelfor="email">Email</label><inputtype="text" name="email" placeholder="john@doe.com" id="email"><labelfor="textarea">Message</label><textareaname="textarea" placeholder="Message" rows="10" id="textarea"></textarea><buttontype="submit" class="btn btn-primary">Send</button></form><scriptsrc="./src/app.js" type="module" async></script></body></html>

Contributing

Feel free to contribute by submitting issues and pull requests. For more detailed documentation, see the source code or contact the maintainers.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Checks and validates a form and returns: a list of errors in JSON format or validation errors directly under the non-validated fields.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages