Skip to content

Instantly share code, notes, and snippets.

@somecallmejosh
Last active November 29, 2016 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save somecallmejosh/3e9dcad4e78d5e77b86dedba155025f1 to your computer and use it in GitHub Desktop.
Save somecallmejosh/3e9dcad4e78d5e77b86dedba155025f1 to your computer and use it in GitHub Desktop.
'use strict';
var form = $('form'),
formFields = $('.atkForm__fields'),
formSubmit = $('.atkForm__submit'),
parentGroup = $('.atkForm__group'),
formError = $('.atkForm__group--error');
$('form input').blur(function() {
var $this = $(this);
// 'has-value' css class adds a bacgkround color the form input
// The input is z-indexed in front of the form label, allowing the
// label to show through if the input is blank. This eliminates
// the issues associated with styling [placeholder] content.
if($this.val()) {
$this.addClass('has-value');
} else {
$this.removeClass('has-value');
}
}).focus(function(){
// If the form group has an `invalid` class (set by the checkForm() below),
// remove the invalid class when the user clicks into the form field.
// This 'hides' the form error message while the user is typing.
var $this = $(this);
if($this.closest(parentGroup).text().length) {
$this.closest(parentGroup).removeClass('invalid');
}
});
function checkForm(e) {
e.preventDefault();
var $this = $(this);
// IF items are invalid, return false.
var invalidFields = false,
requiredFields = $this.find($('[required]'));
$.each( requiredFields, function( i, field ) {
var inlineErrorMessage = $(field).closest(parentGroup).find(formError).text(),
isEmail = $(field).attr('type') === "email";
function showInlineErrorMessage(errorMessage) {
if($(field).val() === '') {
$(field).closest(parentGroup).addClass('invalid');
$(field).closest(parentGroup).find(formError).text(errorMessage);
invalidFields = true;
}
}
if(isEmail) {
// If Email field has a value, run email validation on it.
if($(field).val().length) {
var regexFilter = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var emailText = $(field).val();
if(!regexFilter.test(emailText)) {
$(field).closest(parentGroup).find(formError).text('This is an invalid email');
$(field).closest(parentGroup).addClass('invalid');
invalidFields = true;
}
}
// Otherwise, show default error message for required input that is blank.
showInlineErrorMessage('Email is required');
} else {
// All other fields do not require regex validation.
showInlineErrorMessage(inlineErrorMessage);
}
});
if(invalidFields){
return false;
}
$this.find(parentGroup).hide();
$this.find(formSubmit).hide();
$(this).addClass('form-submitted');
$this.append('<p class="atkForm__submitted">Thanks for submitting this form.</p>');
return true;
}
form.on('submit', checkForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment