我做了一个更容易扩展的替代解决方案。你可以在http://jsbin.com/eyimis/1/上看到它,这里的代码:http: //jsbin.com/eyimis/1/edit
一旦验证了所有输入,它还能够显示提交按钮。
var test = {
// Email
'email' : {
'validate' : 0,
'fn' : function(emailAddress) {
var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern.test(emailAddress);
}
},
// First and last name
'name' : {
'validate' : 0,
'fn' : function(name) {
name = name.split(' ');
// Does it contain two names?
return name.length > 1 && name[1].length > 0;
}
}
}, $error = $('#inputText_infoBox p');
var ready = function () {
// How many inputs do we have to validate?
var inputs = $.map(test, function(n, i) { return i; }).length, score = 0;
for(var key in test) {
// If this input is validated, we have ourselves a score!
if(test[key].validate === 1) {
score++;
}
// Is the amount of scores equal to to amount of inputs?
if(score === inputs) {
return true;
}
}
};
$('input[type=text]').on({
/* We'll check against a validate function every time the user
press a key, depending on what field the user is interacting with */
keyup: function() {
var $this = $(this);
// Run the validate function for this particular input field
if(test[$this.attr('id')].fn($this.val())) {
// Validation returned true, yay! :)
test[$this.attr('id')].validate = 1;
$this.css({'background-color': '#00f000'});
$error.html('');
} else {
// It returned false :(
test[$this.attr('id')].validate = 0;
$this.css({'background-color': '#ffffff'});
}
if(ready()) {
$('#inputText_infoBox').after().html($('<input type="submit">'));
} else {
$button = $('input[type="submit"]');
if(typeof $test !== undefined) {
$button.remove();
}
}
},
/* We'll do the check for empty text fields on blur to
avoid annoying errors */
blur: function() {
var $this = $(this);
// Only run if input hasn't validated yet
if(test[$this.attr('id')].validate === 0) {
if($.trim($this.val()) === '') {
$error.html('Empty field');
}
// The input got to be invalid!
else {
$error.html('Your ' + $this.attr('id') + ' is invalid');
}
}
// It validated, clear error messages
else {
$error.html('');
}
}
});