Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Alex Watts
Alex Watts
8,396 Points

PHP form validation with regular expression


I am creating a website with a form, where the user can enter their details and it will send an email. Validating the form has proven to be really hard. I want to use regular expression to tell the user that they have entered an incorrect postcode and telephone/mobile number. See my code below:

$rxPostcode = "/^[A-Z]{1,2}[0-9R][0-9A-Z]?\s[0-9][ABD-HJLNP-UW-Z]{2}$/";

$rxTelephone = "/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/";

$rxMobile = "/^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/";

if (preg_match($rxPostcode, $postcode) &&
    preg_match($rxTelephone, $telephone) ||
    preg_match($rxMobile, $telephone) &&
    empty($security)) {
 mail($to, $subject, $body);
 header("Location: /thank-you");
} else {
 echo "<h2>An error occured. Return to:</h2>";
 echo "<a href='/'>Solar Panel Funding</a>";

My questions are:

1) How can I test this throughly?

2) How can I display an error message in the HTML page where the form is if the regular expression pattern does not match the users details?