0

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!

1
Contributor
2
Replies
3
Views
7 Years
Discussion Span
Last Post by rouse
0

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;
        }

Edited by rouse: n/a

0

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;
        }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.