I am looking for a correct way to test a JavaScript regular expression for phone number and email address. This includes the RegExp string and the syntax.
First the syntax: I am confused about using the quote mark (“) in defing the RegExp.
Is it

var email_test = new RegExp(/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/);

or

var email_test = new RegExp(“/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/”);

Secondly, what RegExp have you used that works well for phone and email. These are the ones I found for phone and email

var email_test = new RegExp(/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/);

var phone_test = new RegExp(^([\(]{1}[0-9]{3}[\)]{1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$);

Thanks!

From what I have read on the web I would think that these two chunks of code would work, but they don’t.
Is this the general way you would define and test a RegExp object?
Can you give me some ideas of how to test for phone numbers and email addresses?

// Test for a vaild email address
        var email = $('input#email').val();
        var email_test = new RegExp('\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b');
        if (!email_test.test(email)) {
            $('#statusBox').html('<div class="error">I think your email is wrong...</div>');
            return false;
        }

        // Test for a vaild phone number
        var phone = $('input#phone.val();
        var phone_test = new RegExp('^([\(]{1}[0-9]{3}[\)]{1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$');
        if (!phone_test.test(phone)) {
            $('#statusBox').html('<div class="error">I think your phone number is incorrect</div>');
            return false;
        }

Here is a JavaScript solution for both email and phone. The phone as be minimally tested for validation of US phone numbers.

// Test for a vaild email address
        var email_test = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if ( !email_test(email)){
            $('#statusBox').html('<div class="error">I think your email is wrong...</div>');
            return false;
        }

        // Test for a vaild phone number
        var phone_test = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
        if (!phone_test.test(phone)) {
            $('#statusBox').html('<div class="error">I think your phone number is incorrect</div>');
            return false;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.