I am writing a program that allows the user to create a page using a drag-n-drop GUI. Every element (image, text, etc) will have easy-to-use CSS selectors like background-color and font-size, however my client has asked for the ability, when necessary, to add custom CSS to the element as a final option.
Looking past the dangers of users possibly typing in and saving valid javascript functions, trying to style the body tag etc. (I will make sure to handle that by escaping/PDO-handling user input in PHP), how can I write a regex (or another functionality) that tests, crudely, if what the user types in is valid CSS. My regex at the moment is this:
([A-Za-z\-]+?:\s*?[A-Za-z\-]+?;)+?;
And I run it using
var reg = /([A-Za-z\-]+?:\s*?[A-Za-z\-]+?;)+?/;
if (reg.test(textarea.val())) {
console.log("yay");
//add CSS to element
} else {
console.log("nay");
//let user know their input is wrong
}
This works fine to validate
css-selector: css-value;
However, anything after that it will still validate as true because the first part will be true:
css-selector: css-value;
invalid-css is here!
As for what I mean with crudely, all that I find necessary to check is the presence of a : and a ; with text, and possibly a - in-between, it is not necessary to check if the css-selector itself actually exists as a CSS attribute nor if the CSS-value is a valid value of said selector.
Is there a way to ensure the entire input value MUST be true?
As a final note, if you see a potential danger not directly related to inserting script-tags or styling potential whole-page elements that I should be vary of, please let me know
Edit: due to many saying that I can't validate real CSS, I am going to specify my requirement a bit further; first, valid regex:
css-selector: css-value;
other-css-selector: other-css-value;
invalid regex:
css-selector: css-value;
invalid-css is here!
Secondly, what I want is something that validates if I can pass the string to:
$(element).css(validated-string);
And have chrome handle whether what is applied is actually valid, much like it does if you edit CSS live
Secondly, I mention PHP validation, but what I want is to update the CSS live so the user can see the effect of their edits as they add them