Search code examples
htmlformsvalidation

HTML5 Form(elemts) is(are) valid after restoring values from cache - How to fix that?


i am running into an issue here and can't find a solution.

I am saving the entire form into the local storage like so:

contact.form.oninput = (event) => {
        contact.saveFormToBrowserCache();
}
static async saveFormToBrowserCache() {
    let formElements = Tools.qSA("main.contact .contactForm input:not([type=checkbox]), main.contact .contactForm textarea");
    let o = {};
    let cacheKey = await Tools.sha256(contact.formCacheKey);
    formElements.forEach((input) => {
        let inputValue = (input as HTMLInputElement).value
        let key = input.name;
        let value = inputValue;
        if (value !== "") {
            o = {
                ...o,
                [key]: value.trim()
            }
        }
    });
    ls.set(cacheKey, o, {
        encrypt: true
    });
}

that works easily, please ignore those methods which are not mentioned here, they just work. I am restoring the date on page load (if exist) like this:

async restoreFormFromCache() {
    let cacheKey = await Tools.sha256(contact.formCacheKey);
    let formVariables = ls.get(cacheKey, {
        decrypt: true
    }) as Object;
    if (formVariables) {
        Object.entries(formVariables).forEach(entry => {
            const [key, value] = entry;
            let element = Tools.qS("main.contact .contactForm [name=" + key + "]") as HTMLInputElement;
            element.value = value.trim();
        });
        this.messageCurrentChars.innerHTML = this.textarea.value.length.toString();
        this.autoSizeTextArea(this.textarea);
    }
}

and then input elements like this:

<input name=name inputmode=text autocomplete="honorific-suffix given-name additional-name family-name" title="..." type=text minlength=2 required>

become valid even with only one char inserted. I can see this, because i am using ":valid" css selectors and shown an icon. The validation works fine with manual user input. This happens to other input elements as well.

So, how to reset the ":valid|:invalid" state of those elements to respect their required, pattern attributes? I have it online working here: https://trelki.de/kontakt Try it. Enter a single letter as name -> invalid. Then press F5 or reload the page like you want, it restores it and it is shown valid. I am using latest Chrome dev and latest stable. Both the same. Firefox does currently not show the "green check" because i am using the "has()" selector there.


Solution

  • Hm, yesterday i haven't found anything in the web, probably used different keywords. Today i found the solution for this, i still wonder why Browsers behave like this, but its fixed now for me.

    Here: HTML Input validity not checked when value is changed by Javascript