Home

1 minute read

Checking for valid HTML strings in Javascript

Tony Lea

Checking for valid HTML strings in Javascript

I had a scenario where I needed to validate an HTML string to make sure it is correctly structured. In this quick tutorial I will show you an example of how to check if an HTML string is valid using some simple javascript.

🤓 Quick Example

Here is a quick example of a textarea that will check if the contents contains valid HTML. Type in some HTML into the textarea and click the submit button below to check if it contains valid HTML:

Let's see how to create this below 👇

💻 The Code

In this example we're checking the contents of a textarea to see if it contains a valid HTML string. We can easily do this with javascript using the native javascript DOMParser()

let htmlString = '<p>testing</p>';
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, "application/xml");

Next, we can query the parser object and query an element called parsererror, doc.querySelector('parsererror'). If the HTML is invalid this parsererror element will contain a message with the errror.

We can easily wrap this code into a function to check if the input string is valid HTML:

function validateHTML(htmlString){
    let parser = new DOMParser();
    let doc = parser.parseFromString(htmlString, "application/xml");
    let errorNode = doc.querySelector('parsererror');
    document.getElementById('message').innerHTML = '';
    if (errorNode) {
        document.getElementById('message').appendChild(errorNode);
    } else {
        document.getElementById('message').innerText = 'Valid HTML!';
    }
}

From the code above we will output the response to an element with an id of #message. Here is the HTML we need to test everything out:

<textarea id="code"></textarea>

<button onclick="validateHTML(document.getElementById('code').value)" id="submit">Submit</button>

<br>
<div id="message"></div>

When we click the button we fire an onclick() event and pass the contents of the textarea into our new function. If the contents contains valid HTML we'll see a message that says Valid HTML!; otherwise, you'll see an error message that might look like the following:

error-msg.png


I hope this helps you in a future project if you need to check for valid HTML using Javascript 😉