Disscombobilated
Disscombobilated

Reputation: 1

Can't catch error: An invalid form control with name is not focusable

JS try catch does not handle the form submission error "An invalid form control with the name 'somename' is not focusable. I have a tabbed page that shares one submit. When the page loads, the hidden, required field causes bad validation when I move from tab to tab. This would be easy to work around if it triggered a try/catch, and I could look for the message and act appropriately. However, the error skips right by the catch and cannot be handled.

var isValidForm = form.checkValidity();
if (!isValidForm) {
    debugger;
    let subbtn = document.getElementById('hiddenbtn');
    let test = null;
    try {
        test = subbtn.click();
    }
    catch (ex) {
        console.log(ex);
        //if "An invalid form...not focusable" don't 
        //return but continue. We're ok with this error.
    }
    test;
    return;
}

The catch should catch the error. But, instead, it skips right over it. Can anyone tell me how to detect this error in code without the big mess associated with adding and removing several required attributes?

Upvotes: 0

Views: 7138

Answers (2)

Turtlefight
Turtlefight

Reputation: 10700

I created a quick test-case for it:
(Click the test button, the error only appears in the dev console in chrome)

function test() {
  let el = document.querySelector('button[type="submit"]');
  el.click();
  console.log("Still running");
}
.hidden_input { display: none; }
button[type="submit"] { margin-bottom: 0.5rem; }
<form>
  <input type="text" name="hidden_input" class="hidden_input" value="" required />
  <button type="submit">SUBMIT</button>
</form>
<button type="button" onclick="test()">TEST</button>

This error only occurs on Chrome though, not on Firefox (at least from my testing).

I would guess that Chrome doesn't propagate the error as javascript error but rather just logs it.
(Neither window.onerror nor try {} catch {} can handle it)

Your script also continues to execute after the subbtn.click(), so it shouldn't be a problem :)

If you still want to get rid of the error, you can disable form validation on the form or simply submit the form instead of pressing the submit button:

// Disable form validation:
form.noValidate = true;

// Or directly submit the form without using the button:
form.submit();

Upvotes: 1

cWerning
cWerning

Reputation: 633

You have "test = subtn.click()" in the try block, but you call it outside of the block.

Try calling the click function within the try block and you will catch the error as expected.

let test = subtn.click();
try {
    test;
} catch (ex) {
    console.log(ex);
    //if "An invalid form...not focusable" dont return but continue. we're ok with this error
}
return;

Upvotes: 0

Related Questions