Need to disable the submit button if both fields are invalid

22 hours ago 3
ARTICLE AD BOX

It looks like you're mixing up a few things.

Built-in HTML validation uses HTML attributes like required and minlength, for eg

<input type="text" name="ipaddress" required> <input type="text" name="name" minlength="10">

With those attributes you don't need any Javascript at all, the browser will show errors and refuse to submit the form if the fields don't validate against what the attributes specify.

If you want to involve JS, that built-in validation also makes available things like the :is-valid selector, and the .checkValidity() method, on those elements using the built-in validation attributes.

But that only works with those few HTML attributes it supports: required, minlength, etc. For your own more complex validation rules, the browser has no way of knowing what is valid or not, so it can't provide those handy :is-valid or .checkValidity().

So if you want your own rules, you need to handle it all yourself. You're most of the way there already, you're already saving validity state with your own flags:

$thisField.addClass('is-invalid');

Now just check for your own state flags:

// Note your code uses 'addipaddress' but that var does not seem to be defined var isInvalid = ipAddress.classList.contains('is-invalid'); // Or jQuery // var isInvalid = $('#addipaddress').hasClass('is-invalid'); submitBtn.disabled = isInvalid;

If you have multiple inputs which all need to be valid, you can iterate over them all doing the same check:

let valid = true; for (const el of [ipAddress, addhostname, ... list of fields]) { if (el.classList.contains('is-invalid')) { valid = false; break; } } submitBtn.disabled = ! valid;
Read Entire Article