简体   繁体   中英

Set custom HTML5 field validation message from ajax

How would I implement a custom error message coming from the server to display like one of the default HTML 5 error messages.

I'm currently here. However the problem is it only displays the message on the second submit and won't change even if it get the okay from the server(since the submit event will only be fired if it validest correct)

putRequest.onreadystatechange = function() {
    if (putRequest.readyState == XMLHttpRequest.DONE) {
        if (putRequest.status == 200) {

            var json = eval("(" + putRequest.responseText + ")");

            if (!json.success) {
                submitInput.setCustomValidity(json.message);
                submitInput.focus();
                return;
            }else submitInput.setCustomValidity('');

            // go on

        } else {
            alert('An API error occurred');
        }
    }
}

submitNew.addEventListener('submit', function(e) {
    e.preventDefault();

    putRequest.open("GET", "index.php?add&inputURL=" + submitInput.value, true);
    putRequest.send();

});

The problem is that at the point where the submit event is fired, the form has already been validated . If you want to do it yourself you have to do it before.

This means chaning the event submit to click on the button

    putRequest.onreadystatechange = function() {
        if (putRequest.readyState == XMLHttpRequest.DONE) {
            if (putRequest.status == 200) {

                var json = eval("(" + putRequest.responseText + ")");

                if (!json.success) {
                    submitInput.setCustomValidity(json.message);
                    submitInput.focus();

                    return;
                } else submitInput.setCustomValidity('');

                newResultAnswer.innerHTML = json.message;

                newCreateView.style.display = "none";
                newResultView.style.display = "block";

            } else {
                alert('An API error occurred');
            }
        }
    }

    submitForm.addEventListener('submit', function(e) {
            e.preventDefault();
    });

    submitButton.addEventListener('click', function(e) {
            putRequest.open("GET", "index.php?add&inputURL=" + submitInput.value, true);
            putRequest.send();
    });

Remember to also catch the enter key pressed in an input field which also fires the submit. To catch it you'd have to append this.

    submitInput.addEventListener('keydown', function(e) {
        if(e.keyCode == 13) {
            putRequest.open("GET", "index.php?add&inputURL=" + submitInput.value, true);
            putRequest.send(); 
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM