Hands on JavaScript
Brian Moschel of Jupiter IT did a live walkthrough of adding JavaScript functionality to your pages at the May 2009 meetup. He went through adding client side form validation.
Here is the code used in the demo (which mixes JavaScriptMVC and jQuery):
FormController = MVC.Controller.extend('registration_form', /* @Static */ {}, /* @Prototype */ { submit: function(params){ params.event.kill(); var data = params.form_params(); this.check_email(data.email) this.check_username(data.username) if(!this.failed) new MVC.Ajax('/users/create', { parameters: data, onComplete: this.continue_to('after_submit') }) }, after_submit: function(results){ eval(results.responseText); }, success: function(message){ $("#registration_form").css('display','none'); $("#notifier")[0].innerHTML = message; $('#notifier').fadeOut(3000) }, 'input blur': function(params){ if(params.element.type == 'submit') return; var name = params.element.className; var value = params.element.value; this["check_"+name](value); }, check_email: function(value){ var empty_regex = /^\s*$/; var email_regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; // check if its empty if(value.match(empty_regex) != null) this.failure("Email is a required field.", "email") // check if its valid if(value.match(email_regex) == null) this.failure("The email you entered is not a valid email address.", "email") }, check_username: function(value){ var empty_regex = /^\s*$/; // check if its empty if(value.match(empty_regex) != null) this.failure("Name is a required field.", "username") }, failure: function(message, field_type){ var field = $('#registration_form input.'+field_type); field.css('border','2px red solid'); var error_div = $('#registration_form span.'+field_type+"_error"); error_div[0].innerHTML = message; setTimeout(this.continue_to('reset_failure'), 3000); this.failed = true; }, reset_failure: function(){ $('#registration_form input').css('border', ''); var errors = $('#registration_form .error'); for(var i=0; i<errors.length; i++){ errors[i].innerHTML = ""; } }, });
Tags: Brian Moschel, talks
This entry was posted on Sunday, June 14th, 2009 at 11:22 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

