我正在使用jQuery进行验证,如下所示:
$("#register-form").validate({
rules: {
latitude: {
required: true,
strongCoord: true
},
longitude: {
required: true,
strongCoord: true
}
},
messages: {
yrAr: {
required: 'Please enter year.'
}
}
});
$.validator.addMethod('strongCoord', function(value, element) {
return this.optional(element)
value.length >= 4
&& /^-?([0-8]?[0-9]|90).[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180).[0-9]{1,6}$/.test(value);
}, 'Your coordinate format has error'.')
在形式上,文本字段如下:
input class="form-control" name="latitude" placeholder="Enter Latitude" type="text">
<input class="form-control" name="longitude" placeholder="Longitude" type="text">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>
即使我使用了从谷歌获得的坐标,它也不断返回Your coordinate format has error'.
。我敢肯定这只是语法。谁能指出我正确的方向?
提前感谢...
在你的函数中,你可以:
return this.optional(element)
value.length >= 4
&& /^-?([0-8]?[0-9]|90).[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180).[0-9]{1,6}$/.test(value);
但是,这对我来说似乎不是正确的语法。 该文档给出了一个示例,例如:
return this.optional(element) || /^http://mycorporatedomain.com/.test(value);
我认为您需要将代码更改为:
return this.optional(element) ||
(value.length >= 4
&& /^-?([0-8]?[0-9]|90).[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180).[0-9]{1,6}$/.test(value));
解决了...我为纬度和经度创建了 2 个单独的函数,而不是为两者创建了一个函数:
$.validator.addMethod('latCoord', function(value, element) {
console.log(this.optional(element))
return this.optional(element) ||
value.length >= 4 && /^(?=.)-?((8[0-5]?)|([0-7]?[0-9]))?(?:.[0-9]{1,20})?$/.test(value);
}, 'Your Latitude format has error.')
$.validator.addMethod('longCoord', function(value, element) {
console.log(this.optional(element))
return this.optional(element) ||
value.length >= 4 && /^(?=.)-?((0?[8-9][0-9])|180|([0-1]?[0-7]?[0-9]))?(?:.[0-9]{1,20})?$/.test(value);
}, 'Your Longitude format has error.')
然后我这样称呼它:
latitude: {
required: true,
latCoord: true
},
longitude: {
required: true,
longCoord: true
}
为什么我不能同时使用一个函数:(仍然困扰着我