I am fairly new to jQuery and have written the following code to show the user as he/she types in whether or not their password/confirmation is valid. I feel like the code is repetitive and dirty though, and it works well only if the user doesn’t delete part of what they have typed. Then things get sort of wacky.
Here is the js fiddle: http://jsfiddle.net/JCTAc/
Here is the JS *(ignore the checkbox stuff):
$(function() {
$('.checkbox').hide();
$("#password").blur(function(){
var passwordVal = $("#password").val();
var checkVal = $("#password_confirmation").val();
if ( passwordVal.length >=6 ) {
$("#password").css("border","1px solid #9EAD3A");
}
else {
$("#password").css("border","1px solid #E93E3C");
$('.checkbox').hide();
}
});
$("#password_confirmation").keyup(function() {
var passwordVal = $("#password").val();
var checkVal = $("#password_confirmation").val();
if (passwordVal == checkVal) {
if (checkVal.length > 5 ) {
$("#password_confirmation").css("border","1px solid #9EAD3A");
$(".checkbox").show(100);
}
}
else {
$("#password_confirmation").css("border","1px solid #E93E3C");
$('.checkbox').hide();
}
});
$("#password,#password_confirmation").blur(function(){
var passwordVal = $("#password").val();
var checkVal = $("#password_confirmation").val();
if (passwordVal != checkVal) {
$('.checkbox').hide();
$("#password_confirmation").css("border","1px solid #E93E3C");
}
});
});
First off, you shouldn’t set border colors like that in jQuery/javascript. It is important to seperate styling and browser behaviour from each other as much as possible. A better approach is to set a class (.error, .validated for example) and control the styling from the css. Also you repeat yourself in your code a lot. The same functionality is written 3 times. A true sign to break that functionality out to a function.
A tip is also to disable the submit functionality if the input does not validate, and then allowing it if it does.
I reworked it a little. Validating on blur and keyup. I am sure this code can be optimized a lot more as well, but maybe a slight improvement: http://jsfiddle.net/JCTAc/5/