Kaushal Joshi
Kaushal Joshi

Reputation: 41

How to validate css when we add css in textarea value?

I've write css in textarea but need to validate that css which I'm writing it's properties and value is correct or not ?

I've to develop a feature like real time css change along with validating that css For instance if I write .abc { text : text; } then this text is not a valid property nor valid css so I have to show notification/error in textarea itself like : This text is not a valid css

Html Code :

<textarea id="txtCSS" name="txtCSS" rows="14" cols="50">
    .FC{color:blue; margin: 40px; padding: 50px;}
    .cf{color:blue; margin: 40px; padding: 50px; }
</textarea>
<label class="FC">Some Text</label>
<div class="cf">test Text</div>

JavaScript Code :

function render(value) {
        let previewStyle = document.getElementById('previewStyle');
        if (!previewStyle) {
            addStyle(value);
        } else {
            previewStyle.innerText = value;
        }
    }
    function addStyle(styles) {
        /* Create style document */
        const css = document.createElement('style');
        css.type = 'text/css';
        css.id = 'previewStyle';
        if (css.styleSheet) {
            css.styleSheet.cssText = styles;
        } else {
            css.appendChild(document.createTextNode(styles));
        }
        /* Append style to the tag name */
        document.getElementsByTagName("head")[0].appendChild(css);
    }
    const text = document.getElementById('txtCSS');
    text.addEventListener('input', (e) => {
        const content = e.target.value;
        render(content);
    });
    render(text.value);

Referance Image :

enter image description here

Upvotes: 0

Views: 695

Answers (1)

pankaj sondagar
pankaj sondagar

Reputation: 56

You can try like below It should work

   const validatorURL = 'https://jigsaw.w3.org/css-validator/validator' +
  '?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json';
fetch(validatorURL)
  .then(response => response.json())
  .then(results => console.log(results))

Upvotes: 2

Related Questions