Skip to content

Instantly share code, notes, and snippets.

@3stacks 3stacks/form-validation.js
Last active Jan 30, 2017

Embed
What would you like to do?
Functional programming approach to form validation
import generateErrorMessage from 'generate-error-message';
const fields = {
firstName: {
isFieldValid: function() {
const firstName = document.getElementsByName("First_Name")[0].value;
return firstName !== '';
},
userFeedbackElement: document.getElementById("FnameValidation"),
errorMessage: 'Cannot be empty'
},
lastName: {
isFieldValid: function() {
const lastName = document.getElementsByName("Last_Name")[0].value;
return lastName !== '';
},
userFeedbackElement: document.getElementById('LnameValidation'),
errorMessage: 'Cannot be empty'
},
phoneNumber: {
isFieldValid: function() {
const phoneNumber = document.getElementsByName("Phone")[0].value;
const phoneNumberRegex = /^[0-9\s\-\+]{6,14}$/g;
return phoneNumberRegex.test(phoneNumber);
},
userFeedbackElement: document.getElementById("PhoneValidation"),
errorMessage: "Only numbers, '-' and '+' characters are accepted"
},
emailAddress: {
isFieldValid: function() {
const emailAddress = document.getElementsByName("Email")[0].value;
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@+\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailRegex.test(emailAddress);
},
userFeedbackElement: document.getElementById("EmailValidation"),
errorMessage: 'Enter a valid email address'
},
club: {
isFieldValid: function () {
const clubSelectionIndex = document.getElementsByName("Club")[0].selectedIndex;
const clubSelectionValue = document.getElementsByTagName("option")[clubSelectionIndex].value;
return clubSelectionValue !== '';
},
userFeedbackElement: document.getElementById("ClubValidation"),
errorMessage: 'Please select an option'
},
terms: {
isFieldValid: function() {
return document.getElementsByName("T_and_C")[0].checked;
},
userFeedbackElement: document.getElementById("TNCValidation"),
errorMessage: 'Please agree to Terms and Conditions'
}
};
const contactForm = document.getElementById('contact_form');
contactForm.addEventListener('submit', validateFormInputs);
function validateFormInputs(event) {
// Reduce the array of object keys
const isFormValid = Object.keys(fields).reduce((acc, curr) => {
// get the current item from the object
const currentField = fields[curr];
// Call the isFieldValid function in that object
if (currentField.isFieldValid()) {
// The form is valid, so clear the error message
generateErrorMessage(currentField.userFeedbackElement, '');
// Return the accumulative value (may be true/false)
return acc;
} else {
// The form is invalid, so fill it with the canned error message from the object field
generateErrorMessage(currentField.userFeedbackElement, currentField.errorMessage);
return false;
}
}, true);
if (isFormValid) {
contactForm.removeEventListener('submit', validateFormInputs);
return true;
} else {
event.preventDefault();
}
}
window.validateFormInputs = validateFormInputs;
export default function(element, message) {
return element.innerHTML = message;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.