Skip to content

Instantly share code, notes, and snippets.

@yawboakye
Created January 15, 2013 11:44
Show Gist options
  • Save yawboakye/4538064 to your computer and use it in GitHub Desktop.
Save yawboakye/4538064 to your computer and use it in GitHub Desktop.
/* form validation for picket ticket buyer */
(function ($) {
$( function () {
var inputs = $('input');
var buyTicketButton = inputs.last();
buyTicketButton.attr('disabled', 'disabled');
// if the cursor enters and leaves the input field. feedback should be as quickly as possible
inputs.on('blur', validate);
var customerNameIsValid = false
, emailAddressIsValid = false
, phoneNumberIsValid = false
, numberOfTicketsRequestedIsValid = false;
function validate (e) {
var field = $(this).attr('name').trim();
if ( !field ) throw new TypeError('input field should have name attribute set');
switch( field ) {
case 'name' :
case 'title' : customerNameIsValid = validateName.apply(this); break;
case 'email' : emailAddressIsValid = validateEmailAddress.apply(this); break;
case 'phone' : phoneNumberIsValid = validatePhoneNumber.apply(this); break;
case 'tickets' : numberOfTicketsRequestedIsValid = validateIntegerGreaterThanZero.apply(this); break;
}
if ( customerNameIsValid && emailAddressIsValid
&& phoneNumberIsValid && numberOfTicketsRequestedIsValid ) {
console.log('here');
buyTicketButton.removeAttr('disabled');
}
}
function validateName () {
var notice = $('#name-notice');
var name = $(this).val().trim();
if ( name ) {
if ( !!notice.html() )
notice.html('I think I can take that.').addClass('success');
return true;
}
notice.html('So what name do you wanna use?').addClass('error-message');
return false;
}
function validateEmailAddress () {
var EMAIL_REGEX = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var notice = $('#email-notice');
var email = $(this).val().trim();
if ( email && EMAIL_REGEX.test(email)) {
if ( !!notice.html() )
notice.addClass('success').html('email is valid');
return true;
}
notice.html('invalid email').addClass('error-message');
return false;
}
function validatePhoneNumber () {
var notice = $('#phone-notice');
var phone = $(this).val().trim();
if ( phone && phone.length >= 10 && parseInt(phone) ) {
if ( !!notice.html() )
notice.html('Yay! the phone number is valid now').addClass('success');
return true;
}
notice.html('Oops! Take another look at the phone number you entered. I\'ts not valid.')
.addClass('error-message');
return false;
}
function validateIntegerGreaterThanZero () {
var notice = $('#tickets-notice');
var value = parseInt($(this).val().trim());
if ( typeof value === 'number' && value > 0 && (! Math.abs(value - parseInt(value)))) {
if (!!notice.html())
notice.html('Yay! Awesome you!')
return true;
}
notice.html('Oops, did you request for that number of tickets?').addClass('error-message');
return false;
}
});
})(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment