I created a contact form with a text area input only field, which allows the end user to fill out and include a method on how to be contacted. They can choose to enter an email, phone number or both within their message.
I am using jQuery along with javascript to process the form and check if a contact method has been inputted into the message. Here is what I have and it is not getting the job done. Am I doing my matching on the value correctly?
var error = ''
if (value == '' || value == 'Fill out this form and include an email or phone number to be contacted ...') {
error = 'A message along with your contact details are required before sending.';
}
else if (!value.match(/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/) || !value.match(/^[0-9\-\(\)\ ]+$/)) {
error = 'Your message should contain an email address or phone number.';
}
The first error checking works, the 2nd keeps giving an error even if I do enter an email or phone number or both into the message. Should I be breaking this apart and searching each word individually is that how you do it?
There are several problems here, some of which have been pointed out by the other answerers.
Here is a solution which I have found to work:
Search does indeed solve the problem however it is critical that you modify the beginning and end of string delimiters (
^and$) from your RegExs. These would only match their respective targets if they were the only thing in the string being tested. What you want is to find emails and phones as distinct tokens (aka separated from other text by whitespace).To that end, I’ve changed the beginning and end delimiters to be
(\s|^)and(\s|$). These say that the match must have both leading and trailing whitespaces, or be at the beginning or end of the string being matched. This will ensure that you can have phones and emails in your string, and not match something like “adfasdfexample@example.comasdfadfa”Another problem I found was that the phone number RegEx you were using was not sufficient. It was too greedy, and would match a group of numbers with letters in between them. I’ve replaced it with another RegEx that is significantly more robust.
Here’s a jsFiddle to demonstrate this in action: http://jsfiddle.net/T9guw/2/