views:

533

answers:

3

I need to implement a regular expression in my asp.net mvc(C#) application using jquery.

I have a sign in form, in which i need to validate the fields with the required and regular expression.

Putting more clearly, I have Username and Password fields in my Sign in form. I need to validate as required first, and if the user entered any value, then i need to validate with the regular expression.

For ex.: The Username must be minimum 5 characters and no special characters, if entered invalid values. it should say Please enter a valid Username with atleast 5 characters and no special characters.

The Password must be minimum 5 characters and atleast 1 special character, 1 numeric, if entered invalid value, it should say Please enter a valid password with atleast 5 characters and should contain one numer and special character

So i need to give custom messages for each of the fields for required and regular expression.

Is there and common plugin or function to use for regular expression in jquery?

+1  A: 

You don't do regular expressions in jQuery. It's built into JavaScript itself. Of course, there are validation plugins for jQuery that utilize regular expressions.

Check out: http://docs.jquery.com/Plugins/Validation

Most of those plugins should let you enter a custom message to display if it doesn't validate.

Mark
+1  A: 

Username:

/^\w{5,}$/ Five or more word characters (a-z, A-Z, 0-9, and underscore)

Password:

/^(?=.*\d)(?=.*[a-z])(?=_|\W).{5,}$/i A string of at least five chars with minimum one digit, one alphabet (case insensitive) and one special character.

Amarghosh
A: 

Found a common straight forward method implementation in SO :

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        if (regexp.constructor != RegExp)
            regexp = new RegExp(regexp);
        else if (regexp.global)
            regexp.lastIndex = 0;
        return this.optional(element) || regexp.test(value);
    },
    "Please check your input.");

It can be used as:

        $('#signinForm').validate({
            rules: {
                Username: {
                    required: true,
                    regex: "YOURREGULAREXPRESSION"
                }
            },
            messages: {
                Username: {
                    required: "Enter the Username",
                    regex: "Enter the valid Username"
                }
            }
        });

Thus we can have as many custom validation(regex) with custom messages.

Prasad