DDDD
DDDD

Reputation: 3940

How to validate a maximum input of characters with regex

This should be simple, all I want to do is make an input field have a limit of 25 characters using regex.

<script type="text/javascript"><!--
function EnforceMaximumLength(fld,len) {
    if(fld.value.length > len) { fld.value = fld.value.substr(0,len); }
}
//--</script>

<form id="contact" <%--action="contact.html" method="post"--%>>
      <div class="form_settings">
        <p><span>Name</span><input class="contact" type="text"       onkeyup="EnforceMaximumLength(this,25)" name="your_name" value="" /></p>
        <p><span>Email Address</span><input class="contact" type="text" onkeyup="EnforceMaximumLength(this,50)" name="your_email" value="" /></p>
        <p><span>Message</span><textarea class="contact textarea" rows="5" cols="50" name="your_message"></textarea></p>
        <p style="padding-top: 15px"><span>&nbsp;</span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
      </div>
    </form>

What I have is some javascript deleting any characters over limit.

How do you use regex to set a limit?

Upvotes: 2

Views: 4612

Answers (2)

Sam Ruby
Sam Ruby

Reputation: 4340

I agree with maxlength as a solution, but for completeness, here how you would do it with a regular expression:

<input type="text" pattern=".{0,25}"/>

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

No need to use a regex! the input tag has the maxlength attribute:

<input type="text" maxlength="25" />

Upvotes: 3

Related Questions