<!DOCTYPE html> <meta charset="utf-8"> <style> #errorMessage { color: red; } </style> <form> <div id="errorMessage"></div> <label for="name">お名前:</label> <input name="name" id="name" required><br> <label for="password">パスワード:</label> <input type="password" name="password" id="password" required><br> <label for="passwordConfirm">パスワード(確認):</label> <input type="password" name="passwordConfirm" id="passwordConfirm" required><br> <input type="submit" value="送信"> </form> <script> var form = document.forms[0]; form.onsubmit = function(){ form.password.setCustomValidity(""); if(form.password.value != form.passwordConfirm.value){ form.password.setCustomValidity("パスワードと確認用パスワードが一致しません") } } form.addEventListener("invalid", function(){ document.getElementById("errorMessage").innerHTML = "入力値にエラーがあります"; }, false); </script>
あれ? あれ?
うまくいきませんね。。