我的表单在 keyup 上验证,但是当我尝试在提交时验证它时,我只是想不出该怎么做。
这是我的 HTML:
<form action="#" method="post">
<section class="col">
<section class="row">
<label for="name">Name</label>
<input type="text" name="name" value="" id="name" class="field validate-field valid-name" />
</section>
<section class="row">
<label for="email">Email Address</label>
<input type="text" name="email" value="" id="email" class="field validate-field valid-mail" />
</section>
<section class="row">
<label for="phone">Phone Number</label>
<input type="text" name="phone" value="" id="phone" class="field validate-field valid-phone" />
</section>
</section>
<section class="col">
<label for="message">Message</label>
<textarea class="field validate-field valid-text" name="message" id="message-field"></textarea>
<input type="submit" value="Submit" class="submit-button" />
</section>
</form>
JS:
function validate( field ){
var value = field.val();
var to_label = field.parent().find('label');
var error = false;
var error_message = '';
to_label.find('span').remove();
if ( field.hasClass('validate-field') && value == '' ) {
error = true;
error_message = 'Empty Field';
} else if ( field.hasClass('valid-name') && valid_name(value) == false ) {
error = true;
error_message = 'Name must consist characters only';
} else if ( field.hasClass('valid-mail') && valid_email(value) == false ) {
error = true;
error_message = 'Invalid Email';
} else if ( field.hasClass('valid-phone') && valid_phone(value) == false ) {
error = true;
error_message = 'Your phone must be digits only';
};
if ( error == true ) {
to_label.append('<span>'+ error_message +'</span>');
}
};
$('.validate-field').live('keyup', function(){
validate( $(this) );
});
function valid_name(value){
var valid = /^([a-zA-Z_\.\-\+])+$/;
return valid.test(value);
};
function valid_email(value){
var valid = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return valid.test(value);
};
function valid_phone(value){
var valid = /^[0-9-+]+$/;
return valid.test(value);
};
我必须添加这样的内容:
$('form').live('submit', function(){
if ( "...validated..." ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
提交功能应该是什么?
我努力了:
$('form').live('submit', function(){
var valid = validate( $('.field') )
if ( valid == true ) {
$.post('send.php', $('form').serialize(), function(){
alert('sent to PHP.');
})
};
return false;
});
但这会通过所有验证(电子邮件、电话...)验证所有表单。我已经尝试在validation()
函数中添加if (error == false){ return: true }
,然后在提交函数中运行validation()
并添加if ( validation() == true ){ .. to send php ..}
。那也没有用。我需要做什么 ?