最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript input validation with regex - Stack Overflow

programmeradmin5浏览0评论

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

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!

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

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!

Share Improve this question edited May 31, 2016 at 0:57 Mark Chackerian 23.6k6 gold badges114 silver badges105 bronze badges asked May 30, 2016 at 22:36 user5616242user5616242 3
  • When you want to test a whole string, you must describe a whole string (and not only one character). But you can do it in another way, if you build a pattern that must not match the subject (for example using a negated character class with forbidden characters). In this case, you only need to test if the pattern fails and one character suffices. – Casimir et Hippolyte Commented May 30, 2016 at 22:38
  • Use the .each() to cycle through each input element, you are only getting/testing the value of the first one by doing $(":input").val(). – Spencer Wieczorek Commented May 30, 2016 at 22:39
  • thanks for the fast replies! @Casimir et Hippolyte - You're right, I used ! and just checked whether the pattern fails. And @Spencer Wieczorek - (I don't know whether I can do that ) I used $(":input").val().each() but then he does just submit the form without checking the value – user5616242 Commented May 30, 2016 at 22:46
Add a ment  | 

1 Answer 1

Reset to default 10

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();
    ...
});

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;
    }
});

Here is an example Fiddle

发布评论

评论列表(0)

  1. 暂无评论