Floris
Floris

Reputation: 3135

PHP check if it is a valid HTML attribute

I would like to check if a given string could be a valid HTML attribute. If this isn't the case, I will add that string with a prefix of data- to the element. How would I go about this?

For example when the user wants to add a attribute, it passes it to the $attributes array like this:

    $attr = '';
    foreach ( $attributes as $key => $value ) {
        if (is_attr($key)) {
            $attr .= $key . '="' . $value . '" ';
        } else {
            $attr .= 'data-' . $key . '="' . $value . '" ';
        }
    }

So this will finally be added to a form element like an input or textarea or something like that.

... how would the implementation of is_attr($key) look like?

Update: I was hoping I could create the attribute with the DomDocument() class and then validate it to see if the attribute is officially supported. No luck so far.

Upvotes: 4

Views: 841

Answers (1)

Rahul
Rahul

Reputation: 18577

Here is is_attr function to check valid attributes of input or textarea.

function is_attr($attr, $elementType)
{
    $input       = ["autocomplete", "autofocus", "disabled", "list", "name", "readonly", "required", "tabindex", "type", "value"];
    $globalAttrs = ["accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "id", "lang", "style", "tabindex", "title", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "slot", "spellcheck", "translate"];
    $select      = ["autofocus", "disabled", "form", "multiple", "name", "required", "size"];
    $textarea    = ["autocapitalize", "autocomplete", "autofocus", "cols", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "spellcheck", "wrap"];
    return (in_array($attr, $globalAttrs) || in_array($attr, $$elementType));
}
echo is_attr('accesskey','select');

I have taken all the valid attributes from official html doc.

Upvotes: 1

Related Questions