Skip to content

Instantly share code, notes, and snippets.

@adeelhussain
Last active June 21, 2022 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeelhussain/f3f31c1ead036320671a52241d5e41bd to your computer and use it in GitHub Desktop.
Save adeelhussain/f3f31c1ead036320671a52241d5e41bd to your computer and use it in GitHub Desktop.
Form Validations Using Validate.js
/**
* Created by <mr.adi180@gmail.com>Adeel on 19-Jul-16.
*/
'use strict';
var newAccountFormConstraints = {
firstname: {
//First name is required
presence: true,
length: {
//Should be a minimum lenght of 4
minimum: 4
}
},
lastname: {
//last name is required
presence: true,
length: {
//Should be a minimum lenght of 4
minimum: 4
}
},
email: {
// Email is required
presence: true,
// and must be an email (duh)
email: true
},
password: {
// Password is also required
presence: true,
// And must be at least 5 characters long
length: {
minimum: 5
}
},
confirmPassword: {
// You need to confirm your password
presence: true,
// and it needs to be equal to the other password
equality: {
attribute: "password",
message: "^The passwords does not match"
}
}
};
//Init validations here
initValidations('register-form', newAccountFormConstraints);
<form class="form-horizontal" id="register-form" name="register-form" action="/register" method="post" novalidate>
<h2 class="form-signin-heading">Create a new account</h2>
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="firstname" name="firstname" placeholder="First Name" required>
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last Name" required>
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-5">
<input type="email" class="form-control" id="inputEmail3" name="email" placeholder="Email" required>
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-5">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password" required>
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<label for="rPassword" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-5">
<input type="password" class="form-control" id="rPassword" name="confirmPassword" placeholder="Confirm Password" required>
</div>
<div class="col-sm-5 messages"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
<p><a href="/login">Login</a> if you already an account.</p>
</form>
'use strict';
/**
* Form validations function
* @param formId
* @param validationConstraints
*/
function initValidations(formId, validationConstraints) {
//Getting form element by ID
var form = document.getElementById(formId);
//Attaching a listener for submitting form
form.addEventListener("submit", function (ev) {
var errors = validate(form, validationConstraints);
// then we update the form to reflect the results
//If errors then prevent form for submission and show errors
if (errors) {
ev.preventDefault();
showErrors(form, errors || {});
}
});
// Hook up the inputs to validate on the fly
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; ++i) {
inputs.item(i).addEventListener("change", function (ev) {
var errors = validate(form, validationConstraints) || {};
showErrorsForInput(this, errors[this.name])
});
}
// Updates the inputs with the validation errors
function showErrors(form, errors) {
// We loop through all the inputs and show the errors for that input
form.querySelectorAll("input[name]").forEach(function (input) {
// Since the errors can be null if no errors were found we need to handle
// that
showErrorsForInput(input, errors && errors[input.name]);
})
}
// Shows the errors for a specific input
function showErrorsForInput(input, errors) {
// This is the root of the input
var formGroup = closestParent(input.parentNode, "form-group")
// Find where the error messages will be insert into
, messages = formGroup.querySelector(".messages");
// First we remove any old messages and resets the classes
resetFormGroup(formGroup);
// If we have errors
if (errors) {
// we first mark the group has having errors
formGroup.classList.add("has-error");
// then we append all the errors
errors.forEach(function (error) {
addError(messages, error);
})
} else {
// otherwise we simply mark it as success
formGroup.classList.add("has-success");
}
}
// Recusively finds the closest parent that has the specified class
function closestParent(child, className) {
if (!child || child == document) {
return null;
}
if (child.classList.contains(className)) {
return child;
} else {
return closestParent(child.parentNode, className);
}
}
function resetFormGroup(formGroup) {
// Remove the success and error classes
formGroup.classList.remove("has-error");
formGroup.classList.remove("has-success");
// and remove any old messages
formGroup.querySelectorAll(".help-block.error").forEach(function (el) {
el.parentNode.removeChild(el);
})
}
// Adds the specified error with the following markup
// <p class="help-block error">[message]</p>
function addError(messages, error) {
var block = document.createElement("p");
block.classList.add("help-block");
block.classList.add("error");
block.innerText = error;
messages.appendChild(block);
}
}
@adeelhussain
Copy link
Author

  1. Include validate.js from here
    https://validatejs.org/
  2. Include above files two files also customize the form.constraint file according to form fields

Thats all ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment