behz4d
behz4d

Reputation: 1849

jQuery Live Regexp Check

So, I have an input box with default value as "www.mysite.com/users/", here after this values users should be able to define a short URL for themselves, for example: "mike".

Now, I want to only allow a-z and A-Z for the short URL, I want to check the user input live and prevent them to use other characters as &%!"£..., here is my code:

<input type="text" id="short_url" value="www.mysite.com/users/" />
<script>
    ('#short_url').on('keypress', function(){
                var short_url = $(this).val();
                if(short_url.substr(0, 21) != 'www.mysite.com/users/'){
                    $(this).val('www.mysite.com/users/');
                }else{
                    // Only allow a-z
                        short_url = short_url.substr(21);
                        var RegEx = /^[a-z0-9]$/;
                        if(!RegEx.test(short_url)) {
                            if(short_url != '')
                            return false;
                        }
                }
            });
</script>

What I tried in the above code is that not let the user to clear my site.com, so he had to add his short URL after the default value, and also only allow the RegEx to be typed, but it's not working. how should I implement this?

Another thing is that, I also want to allow dot in the short URL, but just 1 dot!

Thanks in advance

Upvotes: 2

Views: 536

Answers (2)

Josh
Josh

Reputation: 44916

Since your base URL will never change... why not just make that static text before your input field. It will drastically simplify your code.

<span>www.mysite.com/users/</span>
<input id="short_url" type="text" />​

And then a little jQuery to handle the validation

(function(){

    var shortUrlRegexp = /^[a-zA-Z]*(\.{1}[a-zA-Z]*)?$/;

    $("#short_url").on("keyup", function(){

        var text = $(this).val();

        var isMatch = shortUrlRegexp.test(text);

        $(this).toggleClass("invalid", !isMatch);

    });

}());​

Here is a live demo.

Upvotes: 1

garyh
garyh

Reputation: 2852

This will allow alpha-numeric + one .. Must start and end with an alpha-numeric char

^[a-z0-9]+\.?[a-z0-9]+$

Upvotes: 0

Related Questions