0

I'm trying to set a custom error message in an HTML5 form with the required attribute, however it doesn't appear to be working.

Code:

<form role="form" method="post" action="contact-form.php">
    <input type="text" class="input-field" name="name" id="name" placeholder="Name" required />
    <input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
    <textarea name="message" class="textarea-field" id="message" placeholder="Message"></textarea>
    <input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />             
</form>
<script>
    var name = document.querySelector( "#name" );
    function setErrorMessage() {
        if ( name.validity.valueMissing ) {
            name.setCustomValidity( "Please enter your name" );
        }
    };
setErrorMessage();
name.addEventListener( "change", setErrorMessage );
 </script>

Fiddle: http://jsfiddle.net/e4eutova/1/

I've looked round and I thought the syntax was correct, but it doesn't appear to be. Any help would be greatly appreciated!

2 Answers 2

1

Nevermind--I found and am using this solution: https://github.com/javanto/civem.js

Sign up to request clarification or add additional context in comments.

Comments

0

As far as I know and understand the problem, you aren't calling the function setErrorMessage() anywhere. You need to add onClick="setErrorMessage() in your submit button input description.

Also, I would try changing the code to use document.getElementById("_your_object_id_"); instead. Or getElementsByName().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.