How to remove oninvalid for every input except one using javascript?

Viewed 355

I created a form with some input fields and the user needs to fill at least one field and if the user doesn't select any then the error will be shown. I achieve that goal but I need to show my custom require message as invalid. Because of the oninvalid on every input, My code is not working properly but I want this message to show so how can I remove oninvalid from the rest of the input fields rather than the filled one?

<form>
    <input name="youtube" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
    <input name="vimeo" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
    <input name="pinterest" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
    <input type="submit" name="submit" value="Submit" id="ls-submit">
</form>

document.addEventListener('DOMContentLoaded', function () {
    const inputs = Array.from(document.querySelectorAll('input[name=youtube], input[name=vimeo], input[name=pinterest]'));
    const inputListener = e => inputs.filter(i => i !== e.target).forEach(i => i.required = !e.target.value.length, i => i.oninvalid  = !e.target.value.length);
    inputs.forEach(i => i.addEventListener('input', inputListener));
});

I really don't have an idea what to do. We can also use alert as an error message and I tried that too but didn't get any success.

1 Answers

You could remove oninvalid and required from all inputs and check it instead with javascript:

var inputs = document.querySelectorAll('input');

document.querySelector('button').addEventListener('click', function() {
    var valid = false;
    for(i = 0; i < inputs.length; i++) {
        if ( inputs[i].value != "" ) {
            valid = true;
            break;
        }
    }
    if (valid) {
        document.querySelector("form").submit();
    }
    else {
        alert('Please fill out at least one social media field');
    }
});

Working example (with 'alert' instead of 'setCustomValidity'):

var inputs = document.querySelectorAll('input');

document.querySelector('button').addEventListener('click', function() {
    for(i = 0; i < inputs.length; i++) {
        var valid = false;
        if ( inputs[i].value != "" ) {
            valid = true;
            break;
        }
    }
    if (valid) {
        document.querySelector("form").submit();
    }
    else {
        alert('Please fill out at least one social media field');
    }
});
<form action="https://stackoverflow.com" method="GET">
    <input name="youtube" value="">
    <input name="vimeo" value="">
    <input name="pinterest" value="">
    <button type="button">submit</button>
</form>

Related