How to use jQuery to onsubmit and check if the value is 2 - 5 characters?

Dora picture Dora · Mar 27, 2013 · Viewed 88.7k times · Source

Let's say I have a text field:

Username: <input type="text" id="username" class="required" />
<input type="submit" />

and I have some jQuery:

$(document).ready(function() {
    user = $("#username");

    user.submit(function() {

    })
})

I want to check if the length of the value entered in username is between 2 - 5 characters after I submit. If it's not then something happens.

I'm not too sure what I should be inside the user.submit(function(){}).

Answer

adeneo picture adeneo · Mar 27, 2013

First you'll need an actual form:

<form id="myForm">
    Username: <input type="text" id="username" class="required" />
    <input type="submit" />
</form>

then:

$(document).ready(function(){
    $('#myForm').on('submit', function(e){
        e.preventDefault();
        var len = $('#username').val().length;
        if (len < 6 && len > 1) {
            this.submit();
        }
    });
});

Or in HTML5 you can use the pattern attribute (not supported in Safari and IE9-and below):

<form id="myForm">
    Username: <input type="text" id="username" pattern=".{2,5}" required />
    <input type="submit" />
</form>

FIDDLE