A simple, configurable input validator for the browser.
Report Bug
·
Request Feature
Table of Contents
To get a local copy up and running follow these simple example steps.
Ways to install
- npm
npm install underage-validate
Note: You cannot<script type="text/javascript" src="path/to/node_modules/underage-validate/underage-validate.min.js"></script>
require
UnderageValidate, it is meant for browsers which do not support that feature.
-
CDN from unpkg
<script type="text/javascript" src="unpkg.com/underage-validate"></script>
-
Download From Releases
<script type="text/javascript" src="path/to/underage-validate.js"></script>
Now that you have UnderageValidate installed, here's how to use it in your code.
-
The constructor takes in an object of
const validator = new UnderageValidate({ errorMessageClass: "error", errorMessageContainerClass: "error-message-container", errorFieldClass: "error" });
rules
, full list of options below.
keyName
(default)
: description
noErrorMessages
(false)
: If true, will not show error messages
errorMessageClass
("error-message")
: CSS class that the error message will be given
errorMessageContainerClass
("error-message-container")
: The class of each container that will hold the error message
staticErrorMessages
(false)
: If true, error messages will all be placed in one static container
staticContainerId
("error-message-container")
: The ID of the static container
noErrorFields
(false)
: If true, will not apply a class to invalid inputs
errorFieldClass
("error-field")
: CSS class that the invalid input will be given
Now that we have our rules set, let's put our validator to use
Assume we have the following page:
-
<form> <div class="error-message-container"> <input id="required" type="text" value="Required" autocomplete="off"> </div> <button id="submit">Submit</button> </form>
Now, in our javascript file we can callform, .error-message-container, .error-message-static-container { display: flex; flex-direction: column; } .error-message { color: red; } .error-field { outline: 1px red solid; }
addField(id, rules)
to start validating fields in our formconst form = document.querySelector("form"); const validator = new UnderageValidate() // No rules set, assuming the defaults .addField("required", { // You can chain wherever makes sense to required: true, message: "This field is required!" }); form.addEventListener("submit", (event) => { event.preventDefault(); validator.validate(); });
validate()
returns aBoolean
, so you may use that value in conjuction with thenoErrorMessages
andnoErrorFields
rules to create custom error messages. Or even perform actions if the form is valid.
Let's take a look at all the field types in more detail
- The
rules
object takes any number of keys needed for a field
Unlike therules
object for each UnderageValidate instance, you must explicitly specify a field type for it to take effect, so there are no defaults
keyName
: description
required
: Requires the field to not be left blank
min
: Defines a minimum character count in the field
max
: Defines a maximum character count in the field
minValue
: Defines a minimum number value in the field
maxValue
: Defines a maximum number value in the field
email
: Validates a field's email using Regex
password
: Validates a password containing 1 letter, 1 number, 8 characters
strongPassword
: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 8 characters
securePassword
: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 1 symbol, 10 characters
regex
: Validates a field using the defined regular expression
matching
: Given a field's id, checks if the values match
message
: Sets the text to display for the error message
Now let's look at a full example to see every way you can configure your instance of UnderageValidate
-
<div class="error-message-container"> <input id="required" type="text" value="Required"> </div> <div class="error-message-container"> <input id="min" type="text" value="Min Chars"> </div> <div class="error-message-container"> <input id="max" type="text" value="Max Chars"> </div> <div class="error-message-container"> <input id="min-value" type="text" value="3"> </div> <div class="error-message-container"> <input id="max-value" type="text" value="10"> </div> <div class="error-message-container"> <input id="email" type="text" value="email@site.com"> </div> <div class="error-message-container"> <input id="password" type="password" value="password123"> </div> <div class="error-message-container"> <input id="strong-password" type="password" value="Password123"> </div> <div class="error-message-container"> <input id="secure-password" type="password" value="Password123!"> </div> <div class="error-message-container"> <input id="regex" type="text" value="Regex"> </div> <div class="error-message-container"> <input id="matching" type="text" value="Password123!"> </div> <button id="submit">Submit</button>
form, .error-message-container, .error-message-static-container { display: flex; flex-direction: column; } .error-message { color: red; } .error-field { outline: 1px red solid; }
const form = document.querySelector("form"); const validator = new UnderageValidate({ noErrorMessages: false, errorMessageClass: "error-message", errorMessageContainerClass: "error-message-container", staticErrorMessages: false, staticContainerId: "error-message-static-container", noErrorFields: false, errorFieldClass: "error-field" }) .addField("required", { required: true, message: "This field is required!" }) .addField("min", { min: 5, required: true, message: "Minimum of 5 characters!" }) .addField("max", { max: 20, required: true, message: "Maximum of 20 characters!" }) .addField("min-value", { minValue: 3, required: true, message: "Minimum value of 3!" }) .addField("max-value", { maxValue: 10, required: true, message: "Maximum value of 10!" }) .addField("email", { email: true, required: true, message: "Invalid email!" }) .addField("password", { password: true, required: true, message: "Invalid password!" }) .addField("strong-password", { strongPassword: true, required: true, message: "Invalid password!" }) .addField("secure-password", { securePassword: true, required: true, message: "Invalid password!" }) .addField("regex", { regex: /[a-zA-Z]/g, required: true, message: "Must match Regular Expression!" }) .addField("matching", { matching: "secure-password", required: true, message: "Passwords do not match!" }); document.querySelectorAll("input").forEach((input) => { input.addEventListener("input", (event) => { validator.validateField(event.target.id); }); }); form.addEventListener("submit", (event) => { event.preventDefault(); validator.validate(); if(document.getElementById("required").value === "Required") validator.invalidateField("required", "Example!"); });
Let's look at a list of all methods tou can use on an instance of UnderageValidate
method(params) -> Return Type
: Description
addField(id, rules) -> UnderageValidate
: Adds a field to be validated. Note: Since UnderageValidate is not form-specific, you can add fields from any input id on a single page
removeField(id) -> UnderageValidate
: Removes a field from validation
modifyField(id, rules) -> UnderageValidate
: Modifies the rules for a field, only replacing the rules passed into the object
replaceField(id, rules) -> UnderageValidate
: Modifies the rules for a field, replacing the rules passed into the object, all others replaced with the defaults
validate() -> Boolean
: Validates all fields added, adding error messages and field classes if applicable
validateField(id) -> Boolean
: Validates the given field added, adding an error message and field class if applicable
invalidateField(id, message) -> UnderageValidate
: Forces an error message onto the given field, useful for recieving errors from a server
getInvalidFields() -> Array[{id, rules}]
: Returns an array of all invalid field objects after validation
getValidFields() -> Array[{id, rules}]
: Returns an array of all valid field objects after validation
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
Andrew Elliott - Discord: @andrewse_#6874 - andrewelliottdev@gmail.com
Project Link: https://github.com/andrewse02/underage-validate