Introduction

You can use regular expressions to validate input in HTML interactive output.

This page provides an example of the validation code as well as commonly used regular expressions.

Input Validation

The following JavaScript example can be used to validate an input format:
3 char – 3 digits. For example ABC-123 .

If the input does not match the required format a message appears and after clicking OK, the field is colored red.

If a user deletes the input, the background color of the field return to grey.

Note that a field can also be mandatory. For more information see Editing Text Options in Editing Interactive Elements.

You can experience using this JavaScript for input validation in Experience Docomotion  – Sample Customer Satisfaction Form.
var regex = /^[A-Za-z]{3}-[0-9]{3}$/;
if (this.value!= "" && !regex.test(this.value))
{
  if (document.getElementsByName(this.name) != null)
     {
      document.getElementsByName(this.name)[0].style.background = "red";
      alert('Enter Valid Code: ABC-123');
      }
}
else
{
 document.getElementsByName(this.name)[0].style.background = "#C0C0C0";}

Examples of Regular Expressions

Following are a few examples of common regular expressions.

1. Number – the input is a number
/^[0-9]*$/;

2. Number within a range – Limit to 45 digits
/^[0-9]{1,45}$/;

3. Only text
/^[a-zA-Z]*$/;

4. Find specific text in a string – Look for first* or second*, “firsts” also matches
b(first?|second?)b;

5. Length does not exceed X characters

  • 3 to 7 characters:
/^[a-zA-Z]{3,7}$/;
  • Exactly 7 characters
/^[a-zA-Z]{7}$/;
  • Minimum 3 characters:
/^[a-zA-Z]{3,}$/;

6. Match date in format of: XX/XX/YYYY
/^(?:(?:31(/|-|.)(?:0?[13578]|1[02]))1|(?:(?:29|30)(/|-|.)(?:0?[1,3-9]|1[0-2])2))(?:(?:1[6-9]|[2-9]d)?d{2})$|^(?:29(/|-|.)0?23(?:(?:(?:1[6-9]|[2-9]d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1d|2[0-8])(/|-|.)(?:(?:0?[1-9])|(?:1[0-2]))4(?:(?:1[6-9]|[2-9]d)?d{2})$/;

7. Valid email
/^(([^<>()[].,;:s@”]+(.[^<>()[].,;:s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/

Note that Docomotion provides a predefined script for validating email addresses.