3

This exact question was asked here:

using the jquery validation plugin, how can I add a regex validation on a textbox?

But unfortunately the solution posted isn't working for me. I am using the very popular jquery validation plugin, specifically this version:

http://jquery.bassistance.de/validate/jquery.validate.js

I tried adding the custom alphanumeric function (from the above stack overflow question) like so:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>

<script type="text/javascript">
$(function() {

    $.validator.addMethod("loginRegex", function(value, element) {
        return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
    }, "Username must contain only letters, numbers, or dashes.");

    $("#myForm").validate({
        rules: {
            "login": {
                required: true,
                loginRegex: true,
            }
        },
        messages: {
            "login": {
                required: "You must enter a login name",
                loginRegex: "Login format not valid"
            }
        }
    });

});
</script>

<form method="post" id="myForm">
    <input type="text" name="login" />  
    <input type="submit" value="Go" />  
</form>

If you run this code you can see that it only validates for some type of input, it doesn't validate the input through the custom alphanumeric function. How can this be made to work?

2
  • What's not working? Type anything except a number, letter, or dash, and you will get the error message (jsfiddle.net/SwEJb) May 26, 2011 at 2:27
  • @Andrew Whitaker you're right, not sure why it wasn't working the other day. I only tried it on the main site where some other code must be conflicting. But in this standalone version it seems to work fine. Thanks.
    – Jim
    May 28, 2011 at 2:53

1 Answer 1

5

Could it be that you have an extra comma after your login rule? IE will have trouble with this:

rules: {
    "login": {
        required: true,
        loginRegex: true,
    }
},

should be:

rules: {
    "login": {
        required: true,
        loginRegex: true
    }
},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.