我正在尝试在没有使用jQuery validation http://的情况下验证网址,但它不起作用。我从这里关注 mtosic 的答案
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
url: "validUrl"
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
当我输入像"www.google.com"这样的地址时,我仍然收到无效错误。
这是小提琴
问题出在哪里?谢谢你的帮助
问题是因为您已经定义了名为 validUrl
的规则,但您仍在$.validate
设置中对元素设置url
规则。另请注意,您希望将布尔值传递给属性,而不是字符串。试试这个:
$(document).ready(function() {
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
validUrl: true // <-- change this
}
},
submitHandler: function(form) {
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>