2

This is my code, checkUsername function doesn't working, how should I fixit?

<form id="register_form" method="post" action="">
    <fieldset>
        <legend>Info</legend>

        <div>
            <label>Username</label>
            <input type="text" name="username" id="username"/>
            <input type="submit" id="btnAccess" class="button" value="Submit" name="btnAccess"/>
    </fieldset>
</form>
$(document).ready(function() {
    var validator = $('#register_form').validate({
        rules: {
            username: {
                required: true,
                minlength: 4,
                checkUsername: true
            }
        },
        messages: {
            username: {
                required: "No blank",
                minlength: "Enter atleast 4 words"
            }
        }
    });

    $.validator.addMethod('checkUsername', function(value, element) {
        return /\s/g.test(value);
    },  "error");
});

http://jsfiddle.net/nambatre/rEpqr/

P/S: if I want to check a string has some words as @, # etc, what should I do?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Killer Whale
  • 55
  • 1
  • 8
  • To check for space, #, or @ characters do this for example: console.log(/[\s@#]/g.test("lol@")); //this example will return true – sajawikio Aug 13 '13 at 09:55

1 Answers1

3

You need to return true is the the value is true

it should be

$.validator.addMethod('checkUsername', function(value, element) {
    return this.optional(element) || !/\s/g.test(value);
}, "error");

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531