使用正则表达式进行JavaScript输入验证 [英] JavaScript input validation with regex
本文介绍了使用正则表达式进行JavaScript输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想验证我的输入,因此用户只需输入字母即可.问题是它只检查一个输入字段,但是我用:input
I want to validate my inputs, so the user can just enter letters. The problem is that it just checks one input field but I selected all with :input
代码:
$('#formularID').submit(function() {
var allInputs = $(":input").val();
var regex = new RegExp("[a-zA-Z]");
if(regex.test(allInputs))
{
alert("true");
}else
{
alert("false");
return false;
}
});
我非常感谢我所能提供的一切帮助!
I appreciate every help I can get!
推荐答案
Firstly you need to cycle through each of your input elements, you can do this by using .each()
:
// Cycles through each input element
$(":input").each(function(){
var input = $(this).val();
...
});
接下来,您的RegExp仅检查第一个字符是否为字母,如果要确保只有一串字母可以匹配,则可以改用^[a-zA-Z]+$
:
Next your RegExp is only checking for the first character to be a letter, if you want to ensure that only a steam of letters can match you will want to use ^[a-zA-Z]+$
instead:
$(":input").each(function(){
var input = $(this).val();
var regex = new RegExp("^[a-zA-Z]+$");
if(regex.test(input)) {
alert("true");
}else {
alert("false");
return false;
}
});
这篇关于使用正则表达式进行JavaScript输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文