27

I want to know if there is any way to programatically show a HTML5 validation error, using a JavaScript function.

This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.

I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).

JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/

HTML Form:

<form>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</form>

<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>

JavaScript:

function triggerCustomMsg()
{
    document.getElementById("email").setCustomValidity("This email is already used");

}

The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.

4

4 に答える 4

35

HTMLFormElement.reportValidity() メソッドを使用できるようになりました。現時点では、Internet Explorer を除くほとんどのブラウザーで実装されています ( MDN のブラウザーの互換性を参照してください)。送信イベントをトリガーせずに有効性エラーを報告し、同じ方法で表示されます。

于 2016-08-28T18:39:05.817 に答える