'How to make a regex for textarea?

I have this code

var message_regex = /^.{10,500}$/;

I want the user to enter a minimum of 10 characters, But it doesn't matter how much words I enter my error code still shows up. If I remove the 500 from the code above everything works fine. I just want to know if my regex code is fine or am I missing something? This is my jquery code for the regex

if(message == ""){
    $(".val_message").html("Please enter an inquiry").addClass('validate');
    validation_holder = 1;
} else {
    if(!message_regex.test(message)) {
        $(".val_message").html("Your message is too short please enter atleast 10 characters").addClass('validate');
        validation_holder = 1;
    } else {
    $(".val_message").html("");
    }
  }

Also if I put change the code to

var message_regex   = /^.{5,500}$/;

It doesn't care if I enter one character. What could be wrong?



Solution 1:[1]

Do you really need regex for this. This validation can be done like this also:

// assuming ta is your textarea element
var maxlen = 500;
var minlen = 5;
if(ta.value.length > maxlen) { 
    $(".val_message").html("Enter at most " + maxlen + " characters in the textarea");
    ta.value = ta.value.substr(0, maxlen); 
}
else if(ta.value.length < minlen) { 
   $(".val_message").html("Enter at least " + minlen + " characters in the textarea");
}

Solution 2:[2]

i think the regex should look like this

var messageregex = /^[A-Za-z0-9]{10}*$/

Solution 3:[3]

I found my problem guys. I feel so dumb!! Probably cause it's 3 am.

<textarea id="message" class="cfMsg" name="message" placeholder="Your inquiry"></textarea>

My problem was the name="message" I had it like name="name" when I changed it my regex coded worked :/ Sorry! and thanks for the help I learned a new way of doing it from @anubhava

Solution 4:[4]

Nowadays, it would probably be easiest to use the minlength and maxlength attributes on the textarea, which have been available for many years now:

<textarea
  id="message"
  class="cfMsg"
  name="message"
  minlength="10"
  maxlength="500"
  placeholder="Your inquiry"></textarea>

The only downside is that IE does not support minlength, but that might not be a problem these days.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anubhava
Solution 2 user2849138
Solution 3 andresr
Solution 4 Oliver