From f807bc25d1123d7296c6549514b03dfe8e8018c0 Mon Sep 17 00:00:00 2001 From: Dan Hansen Date: Thu, 13 Jan 2011 01:24:05 -0600 Subject: [PATCH] whitelist certain keyCodes, e.g. tab, fixes #795 --- public/javascripts/validation.js | 14 +++++++++++--- spec/javascripts/validation-spec.js | 9 +++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/public/javascripts/validation.js b/public/javascripts/validation.js index e932e49db..5f80f4aaa 100644 --- a/public/javascripts/validation.js +++ b/public/javascripts/validation.js @@ -12,19 +12,27 @@ var Validation = { characters: /^(([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,}))(, *(([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})))*$/ } }, + whiteListed: function(keyCode) { + var keyCodes = [0, 37, 38, 39, 40, 8, 9]; + return $.grep(keyCodes, function(element) { return keyCode !== element; }).length === keyCodes.length - 1; + }, + events: { usernameKeypress: function(evt) { - if(evt.keyCode === 0) { + if(Validation.whiteListed(evt.keyCode)) { return; } + if(!Validation.rules.username.characters.test(this.value + String.fromCharCode(evt.keyCode))) { evt.preventDefault(); } - }, + }, + emailKeypress: function(evt) { - if(evt.keyCode === 0) { + if(Validation.whiteListed(evt.keyCode)) { return; } + if(!Validation.rules.email.characters.test(this.value + String.fromCharCode(evt.keyCode))) { $('#user_email').css('border-color', '#8B0000'); } else { diff --git a/spec/javascripts/validation-spec.js b/spec/javascripts/validation-spec.js index f289f926d..41eed51a6 100644 --- a/spec/javascripts/validation-spec.js +++ b/spec/javascripts/validation-spec.js @@ -15,6 +15,15 @@ describe("Validation", function() { }); }); }); + describe("whiteListed", function() { + it("returns true if the keyCode is whitelisted", function() { + expect(Validation.whiteListed(0)).toBeTruthy(); + }); + + it("returns false if it's not", function() { + expect(Validation.whiteListed(9001)).toBeFalsy(); + }); + }); describe("events", function() { describe("usernameKeypress", function() { it("doesn't allow the user to type anything but letters, numbers and underscores", function() {