在下面的代码中,iam使用jquery验证..
问题仅适用于FullName字段..当我刚输入一个FullName为“tom”时,它应该显示一些错误,但它当前没有显示...当我输入某些'harry potter'时BUt(或者'harry-potter',它不应该显示任何错误....
<!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() {
$('#fullname').focus();
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/>
Select Country: <select>
<option value="South Yorkshire" selected>South Yorkshire</option>
<option value="Rest of England">Rest of England</option>
<option value="Wales, Scotland">Wales, Scotland</option>
<option value="Northern Ireland">Northern Ireland</option>
<option value="European Union">European Union</option>
<option value="Rest of World">Rest of World</option>
<option value="Other">Other</option>
</select><br/>
<input type="submit">
</form>
</body>
</html>
请检查某人..
答案 0 :(得分:1)
以下是如何在单个正则表达式中执行所有操作:
var validCharactersRegex = /^[a-z][- a-z]*[- ]{2}[- a-z]*[a-z]$/i;
function fullname_valid(value) {
return validCharactersRegex.test(value);
}
$.validator.addMethod("custom_fullname", function(value, element) {
return fullname_valid(value);
}, 'Your Name should be entered like: "blahblah"');
这要求它以字母开头,以字母结尾,仅包含字母,空格和短划线,并且在某处包含空格 - 空格,破折号,空格 - 破折号或破折号空间的分隔符它
请参阅FIDDLE