我正在为表单字段进行 jQuery 验证
我似乎无法使以下工作:
- 我的
Full Name
字段需要像:roger federer
或roger-federer
(当前验证也接受一个单词,这是不允许的。 - 我不需要
submit
按钮,但现在我只是保留了它,以便让它暂时工作。
有人可以告诉我如何在没有submit
按钮的情况下实现验证吗?
代码 :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>
<script>
$(document).ready(function() {
var validCharactersRegex = new RegExp(/^[a-z -]+$/);
var doesNotStartWithDashOrSpace = new RegExp(/^[^ -]/);
var fullname_invalid = function(value) {
return validCharactersRegex.test(value) && doesNotStartWithDashOrSpace.test(value) && value.indexOf(' ') == -1 && value.indexOf('--') == -1 && value.indexOf(' -') == -1 && value.indexOf('- ') == -1;
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_invalid(value);
}, 'Your Name should be entered like: "blahblah"');
$('#signup').validate({
rules: {
fullname: {
required: true,
custom_fullname: true
},
email: {
required: true,
email: true
}
},
messages: {
fullname : {
required: "Please specify your Full Name",
custom_fullname : "Your Name should be entered like: fullname lastname (or) fullname-lastname"
},
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
});
$('#signup').on('submit', function(event) {
event.preventDefault();
});
$("#phone").mask("(9999) 9999999");
});
</script>
<style>
.error {color: red;}
</style>
</head>
<body>
<form id="signup" action="/action">
Full Name: <input name="fullname" type="text" maxlength="14" /><br/>
Email <input id="email" name="email" size="25" class="required email" /><br/>
Telephone Number: <input type="text" name="phone" id="phone" /><br/>
<input type="submit">
</form>
</body>
</html>