whitelist certain keyCodes, e.g. tab, fixes #795

This commit is contained in:
Dan Hansen 2011-01-13 01:24:05 -06:00
parent 43658b4923
commit f807bc25d1
2 changed files with 20 additions and 3 deletions

View file

@ -12,19 +12,27 @@ var Validation = {
characters: /^(([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,}))(, *(([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})))*$/ 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: { events: {
usernameKeypress: function(evt) { usernameKeypress: function(evt) {
if(evt.keyCode === 0) { if(Validation.whiteListed(evt.keyCode)) {
return; return;
} }
if(!Validation.rules.username.characters.test(this.value + String.fromCharCode(evt.keyCode))) { if(!Validation.rules.username.characters.test(this.value + String.fromCharCode(evt.keyCode))) {
evt.preventDefault(); evt.preventDefault();
} }
}, },
emailKeypress: function(evt) { emailKeypress: function(evt) {
if(evt.keyCode === 0) { if(Validation.whiteListed(evt.keyCode)) {
return; return;
} }
if(!Validation.rules.email.characters.test(this.value + String.fromCharCode(evt.keyCode))) { if(!Validation.rules.email.characters.test(this.value + String.fromCharCode(evt.keyCode))) {
$('#user_email').css('border-color', '#8B0000'); $('#user_email').css('border-color', '#8B0000');
} else { } else {

View file

@ -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("events", function() {
describe("usernameKeypress", function() { describe("usernameKeypress", function() {
it("doesn't allow the user to type anything but letters, numbers and underscores", function() { it("doesn't allow the user to type anything but letters, numbers and underscores", function() {