Javascript 表单验证;获取所有“输入类型=文本”并验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4010356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Form validation; Get all "input type=text" and validate?
提问by Gabi Purcaru
I have a form which is dynamic.
我有一个动态的表格。
That means, the inputs names are changed, and not the same, but they are all the same "TYPE".
这意味着,输入名称已更改,并且不相同,但它们都是相同的“类型”。
So I need to have a javascript which gets all input type="text"and validates them. Is this possible?
所以我需要一个 javascript 来获取所有输入 type="text"并验证它们。这可能吗?
If so, how?
如果是这样,如何?
All I need to check is so that they are not empty, and that they are only numeric.
我需要检查的是它们不是空的,并且它们只是数字。
Thanks
谢谢
回答by Gabi Purcaru
Use document.querySelectorAll("input[type=text]")
to get the array with all inputs of type "text". You need to iterate through them and validate.
用document.querySelectorAll("input[type=text]")
得到,类型为“文本”的所有输入数组。您需要遍历它们并进行验证。
Also note that you will probably want to use something like #container_id input[type=text]
to make sure you won't get any nodes that you don't need.
另请注意,您可能希望使用类似的方法#container_id input[type=text]
来确保不会获得任何不需要的节点。
Here is a sample of how your validation should look:
以下是您的验证外观示例:
var nodes = document.querySelectorAll("#container_id input[type=text]");
for (var i=0; i<nodes.length; i++)
if (nodes[i].value == "" || !/[0-9.]+/.test(nodes[i].value))
return "invalid.";
return "valid";
回答by dev-null-dweller
Something like that:
类似的东西:
var inp = document.getElementsByTagName('input');
for(var i in inp){
if(inp[i].type == "text"){
if(!/^\d{1,}$/.test(inp[i].value)){
alert('Invalid value detected');
inp[i].focus();
break;
}
}
}