Features

All codeless features →

All advanced features →

Codeless Browser Test Automation

For those new to testing

Email testing

API & third-party integrations

Web test recorder

Codeless test editor

Visual testing

Accessibility testing

Browsers, screens & geolocations

Advanced scheduling

Advanced End-to-End Testing Capabilities

For experienced testers

ALSO INCLUDES

Solutions

QA testers

Build, run, and manage test suites at scale

Engineers

CI/CD hooks, API access, JS execution

Product managers

Visibility into quality without the code

See it in action

Request a personalized demo →

Pricing
Resources

Getting started

Everything you need to run your first test

Documentation

Features, API, integrations and settings

Support

Our team is here to help

Success stories

Real reviews from Ghost Inspector customers

Ghostwriter blog

QA and testing, written by the Ghost Inspector team

Latest articles on browser automation, CI/CD, and more

About Us Blog
Start free trial

Regex for Validating the HTML id Attribute

Ghost Inspector is an automated web testing tool that helps QA testers and engineers to easily build, edit, and run low-code/no-code web tests. Start a free trial.


When we initially started building our test recorder, we needed a way to validate the id attributes being used on the page. We would sometimes capture an id attribute in a recording, only to find that it failed when we used it in a test, because it didn’t meet specification. For instance, sometimes websites would use an id with a number in front, like this:

<div id="5-answer"><!-- … --></div>

That is technically invalid, at least in the HTML4 specification:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-“), underscores (“_”), colons (“:”), and periods (“.”).

The HTML5 specification is a little more lax. It’s only requirement is that “the value must not contain any space characters.” However, many websites are still technically using HTML4, so sometimes these still need to be validated. Luckily, you can test for these requirements with a simple regular expression. Here’s the function in Javascript:

function isCssIdValid(id) {
  re = /^[A-Za-z]+[\w\-\:\.]*$/
  return re.test(id)
}

First, we make sure that the id starts with a letter, then we ensure the rest of it is an alphanumeric character, an underscore, a dash, a colon or a period. Note that the \w is the equivalent of [A-Za-z0-9_].

That’s it! 

Set up automated QA testing with Ghost Inspector

Our 14 day free trial gives you and your team full access. Create tests in minutes. No credit card required.