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.

Saint Robson
  • 5,475
  • 18
  • 71
  • 118

2 Answers2

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

Tats_innit
  • 33,991
  • 10
  • 71
  • 77
  • 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? – Saint Robson Jul 04 '12 at 10:28
  • @RobertHanson hiya bruv do this: `/^[A-Za-z][a-z0-9\-\s]+$/i` or this link will help in detail `:)` this should help: http://stackoverflow.com/questions/1303746/how-can-i-verify-that-user-name-starts-with-a-letter-and-contains-only-alphanume – Tats_innit Jul 04 '12 at 10:33
  • @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 : http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation , it will be 30 mins read + some other good regex article and I reckon you will be happy ever after `:)` Hope this helps man! – Tats_innit Jul 04 '12 at 12:45
1

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

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