我试图验证输入字段,以查看输入的值是否包含字符串开头的数字或字母X或Y:
var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];
for(var i=0, l=t_index_array.length; i < l; i++){
if (document.form.topography_index.value.toUpperCase().substr(0,1) != t_index_array[i]){
alert ( "The Topography index field needs to start with a number between 0 and 9 or the letters X or Y." );
valid = false;
return valid;
}
}由于t_index_arrayi的值总是为0,所以这是不起作用的。有什么想法吗?
发布于 2013-11-18 05:04:37
当前的逻辑是检查它是否以每个字符开始,而不是其中的一个字符(这当然是不可能的)。
相反,你的意思是:
var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];
if(!t_index_array.some(function(val) {
return document.form.topography_index.value.toUpperCase().substr(0,1) == val
})) {
alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
return false;
}
return true;但我会用正则表达式,这就更简单了。
if(!/^[0-9xy]/i.test(document.form.topography_index.value)) {
alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
return false;
}
return true;编辑:/^[0-9xy]/i的解释。
^匹配在输入开始。[0-9xy]字符0到9,或x,或yi案例-无意义发布于 2013-11-18 05:05:18
你可以用regex来处理这个案子。
var patt1 = /^[\dXY]/i;
var result =inputfield.match(patt1);
//the result will hold the expected output如果结果是null..then,则它不以数字或x或y开头
谢谢你@RobG
https://stackoverflow.com/questions/20040392
复制相似问题