简体   繁体   English

使用正则表达式进行JavaScript输入验证

[英]JavaScript input validation with regex

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 问题是它只检查一个输入字段,但我选择all :input

code: 码:

$('#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() : 首先,您需要遍历每个输入元素,您可以使用.each()来完成此操作:

// Cycles through each input element
$(":input").each(function(){
    var input = $(this).val();
    ...
});

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: 接下来你的RegExp只检查第一个字符是否为字母,如果你想确保只有一串字母可以匹配你想要使用^[a-zA-Z]+$代替:

$(":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;
    }
});

Here is an example Fiddle 这是一个小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM