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?

Community
  • 1
  • 1
Jim
  • 327
  • 2
  • 3
  • 5
  • What's not working? Type anything except a number, letter, or dash, and you will get the error message (http://jsfiddle.net/SwEJb/) – Andrew Whitaker May 26 '11 at 02: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 '11 at 02:53

1 Answers1

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
    }
},
ScottE
  • 21,530
  • 18
  • 94
  • 131