HTML5 Form Validation With Regex

There are two ideas that enters the scene now:

  • The tag has new type attribute values like url, email, date, telephone number, and color.
  • The tag has the new attribute pattern where you can describe allowed input with a regex.

Here are three pragmatic (but not globally perfect) examples I created:

Strong password: <input title="at least eight symbols containing at least one number, one lower, and one upper letter" type="text" pattern="(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required />

Email address: <input type="text" title="email" required pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}" />

Phone number: <input type="text" required pattern="(+?d[- .]*){7,13}" title="international, national or local phone number"/>

Validate Number field in Contact Form 7

Allow numbers only in ‘number’ field in Contact Form 7 plugin, add the following code in your functions.php

Validate Numbers in Contact Form 7
This is for 10 digit numbers

function is_number( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];

if ($name == 'request-phone') {
$stripped = preg_replace( '/D/', '', $_POST[$name] );
$_POST[$name] = $stripped;
if( strlen( $_POST[$name] ) != 10 ) { // Number string must equal this
$result['valid'] = false;
$result['reason'][$name] = $_POST[$name] = 'Enter 10 digit phone number.';
return $result;

add_filter( 'wpcf7_validate_text', 'is_number', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'is_number', 10, 2 );

How to call it in the admin section

[number request-phone]

Replace “request-phone” with your field name.