underage-validate v1.1.0
Getting Started
To get a local copy up and running follow these simple example steps.
Installation
Ways to install
npm
```bash npm install underage-validate ``` ```html <script type="text/javascript" src="path/to/node_modules/underage-validate/underage-validate.min.js"></script> ``` _**Note:** You cannot `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>
Usage
Now that you have UnderageValidate installed, here's how to use it in your code.
The Basics
The constructor takes in an object ofconst validator = new UnderageValidate({ errorMessageClass: "error", errorMessageContainerClass: "error-message-container", errorFieldClass: "error" });
rules
, full list of options below.keyName
(default)
: descriptionnoErrorMessages
(false)
: If true, will not show error messageserrorMessageClass
("error-message")
: CSS class that the error message will be givenerrorMessageContainerClass
("error-message-container")
: The class of each container that will hold the error messagestaticErrorMessages
(false)
: If true, error messages will all be placed in one static containerstaticContainerId
("error-message-container")
: The ID of the static containernoErrorFields
(false)
: If true, will not apply a class to invalid inputserrorFieldClass
("error-field")
: CSS class that the invalid input will be given
Adding Fields
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>
form, .error-message-container, .error-message-static-container { display: flex; flex-direction: column; } .error-message { color: red; } .error-field { outline: 1px red solid; }
Now, in our javascript file we can call
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.
Field Types
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 defaultskeyName
: descriptionrequired
: Requires the field to not be left blankmin
: Defines a minimum character count in the fieldmax
: Defines a maximum character count in the fieldminValue
: Defines a minimum number value in the fieldmaxValue
: Defines a maximum number value in the fieldemail
: Validates a field's email using Regexpassword
: Validates a password containing 1 letter, 1 number, 8 charactersstrongPassword
: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 8 characterssecurePassword
: Validates a password containing 1 lowercase letter, 1 uppercase letter, 1 number, 1 symbol, 10 charactersregex
: Validates a field using the defined regular expressionmatching
: Given a field's id, checks if the values matchmessage
: Sets the text to display for the error message
Full Example
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!"); });
All instance methods
Let's look at a list of all methods tou can use on an instance of UnderageValidate
method(params) -> Return Type
: DescriptionaddField(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 pageremoveField(id) -> UnderageValidate
: Removes a field from validationmodifyField(id, rules) -> UnderageValidate
: Modifies the rules for a field, only replacing the rules passed into the objectreplaceField(id, rules) -> UnderageValidate
: Modifies the rules for a field, replacing the rules passed into the object, all others replaced with the defaultsvalidate() -> Boolean
: Validates all fields added, adding error messages and field classes if applicablevalidateField(id) -> Boolean
: Validates the given field added, adding an error message and field class if applicableinvalidateField(id, message) -> UnderageValidate
: Forces an error message onto the given field, useful for recieving errors from a servergetInvalidFields() -> Array[{id, rules}]
: Returns an array of all invalid field objects after validationgetValidFields() -> Array[{id, rules}]
: Returns an array of all valid field objects after validation
Contributing
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
Contact
Andrew Elliott - Discord: @andrewse_#6874 - andrewelliottdev@gmail.com
Project Link: https://github.com/andrewse02/underage-validate