Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validator : Validate AlphaNumeric + Space and Dash

Tags:

jquery

php

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.

like image 906
Saint Robson Avatar asked Jul 04 '12 10:07

Saint Robson


People also ask

How can check date format is correct or not in jQuery?

Above ValidateDate() function will check the argument value against this regular expression. If the entered value is in mm/dd/yyyy or mm-dd-yyyy format then this function will return true, otherwise false.

How do I show different errors in jQuery validator addMethod?

validator. addMethod('min-length', function (val, element) { // do stuff // the error message here needs to be dynamic }, 'The field cannot be less than than ' + element. attr('data-min') + // it is within the closure, but it can't grab it ' length. ');

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

How do you check if jQuery validate is loaded?

fn , so simply check whether it exists or not; if (typeof jQuery. fn. validationPlugin === "function") { // It's loaded } else { // It's not. }


2 Answers

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

like image 93
Tats_innit Avatar answered Oct 12 '22 23:10

Tats_innit


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

[A-za-z0-9_\-\s]+
like image 33
Vladimir Kadalashvili Avatar answered Oct 12 '22 23:10

Vladimir Kadalashvili