9

I have jQuery validation plugins (http://docs.jquery.com/Plugins/Validation) installed on my website.

I'm using this code to validate alpha-numeric from text field, and it works. but it doesn't allow space and dash (-).

$.validator.addMethod("titleAlphaNum", function(value, element, param) 
{
return value.match(new RegExp("^" + param + "$"));
}); 

how to make it works with space and dash? thanks.

0

2 Answers 2

27

working demo http://jsfiddle.net/cAADx/

/^[a-z0-9\-\s]+$/i should do the trick!

g = /g modifier makes sure that all occurrences of "replacement"

i = /i makes the regex match case insensitive.

good read: http://www.regular-expressions.info/javascript.html

Hope this helps,

code

$(function() {

    $.validator.addMethod("loginRegex", function(value, element) {
        return this.optional(element) || /^[a-z0-9\-\s]+$/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"
            }
        }
    });

});​

Will remove this image in 2 mins see here robert like this http://jsfiddle.net/5ykup/

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

bro, your code allows user to enter space and/or dash as first character. how to make first character entered by user MUST BE alpha-numeric only?
@RobertHanson hiya bruv do this: /^[A-Za-z][a-z0-9\-\s]+$/i or this link will help in detail :) this should help: stackoverflow.com/questions/1303746/…
@RobertHanson No Worries bruv :) I am about to sleep now its very very late at my end, You can create specific Regex function same as one above or read this : stackoverflow.com/questions/280759/… , it will be 30 mins read + some other good regex article and I reckon you will be happy ever after :) Hope this helps man!
2

I think it will work if you pass the following RegExp as param:

[A-za-z0-9_\-\s]+

1 Comment

Hiya I reckon this will still not allow spaces, just a note :) add \s is for space

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.