[英]Using jQuery validation plugin to check an array called by a Google visualization api query
I'm using the jQuery validation plugin to check my student's ids when they log into class. 我正在使用jQuery验证插件来检查我的学生登录到课堂时的ID。 Validating against an array using the following code works fine.
使用以下代码对数组进行验证可以正常工作。
jQuery.validator.addMethod("studentID", function(value) {
var ID = ['109289','109351'] /* Just a few Ids, but this works fine. */
var in_array = $.inArray(value, ID);
if (in_array == -1) {
return false;
}else{
return true;
}}, "SORRY, NOT A VALID ID!"); $("#validID").validate({ success: function() {
alert("It works!");} });
What I'm interested in doing is validating against an array which is called to an input field using google visualization api query each time the page loads. 我有兴趣做的是针对每次页面加载时使用Google可视化api查询调用到输入字段的数组进行验证。 I'm having difficulty figuring out how to change the validation script to look at the input field's array of Ids.
我很难弄清楚如何更改验证脚本以查看输入字段的ID数组。 Is this even possible?
这有可能吗?
And here's the validation code with my (failed) attempt: 这是我(失败)尝试的验证代码:
jQuery.validator.addMethod("studentID", function(value) {
var ID = document.getElementById("valIDS_out").value; /* Doesn't work??? */
var in_array = $.inArray(value, ID);
if (in_array == -1) {
return false;
}else{
return true;
}}, "SORRY, NOT A VALID ID!");
$("#validID").validate({ success: function() {
alert("It works!");} });
Thanks for any assistance you can provide. 多谢您提供的协助。 I'm very new at this.
我对此很陌生。
The problem is your ID
variable is a string, not an array. 问题是您的
ID
变量是字符串,而不是数组。 You need to convert it to an array before calling $.inArray()
. 您需要在调用
$.inArray()
之前将其转换为数组。
If the string were formatted like the following: 如果字符串的格式如下:
"111111",222222","333333"
You could easily convert it to an array by using the JSON.parse()
function: 您可以使用
JSON.parse()
函数将其轻松转换为数组:
var ID = JSON.parse('[' + document.getElementById("valIDS_out").value + ']');
But there are three things wrong with your string: 但是您的字符串有三点错误:
JSON.parse()
requires double quotes. JSON.parse()
需要双引号。 That is, your string looks like this: 也就是说,您的字符串如下所示:
111111','222222','333333',
To correct all this, you could use: 要更正所有这些,您可以使用:
var ID = JSON.parse('["' + document.getElementById("valIDS_out").value.slice(0,-1).replace(/\'/g, '"') + ']');
And you can shorten the next line to: 您可以将下一行缩短为:
return ($.inArray(value, ID) >= 0);
As John S said, ID isn't an array, it's simply a string, and it's not valid JSON which may be parsed. 正如John S所说,ID不是一个数组,它只是一个字符串,并且不是可以解析的有效JSON。
Possible solution which works with the given String: 适用于给定String的可能解决方案:
jQuery.validator.addMethod("studentID", function(value) {
var ID = document.getElementById("valIDS_out").value;
return ((!isNaN(value) && ID.match(new RegExp('\\b'+value+'\\b'))));
}, "SORRY, NOT A VALID ID!");
http://codepen.io/anon/pen/RWPwdo http://codepen.io/anon/pen/RWPwdo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.