Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
You will have to trigger submission of the form to get the message to appear –  Explosion Pills Jul 9 at 14:07
 
http://jsfiddle.net/tjXG3/2/ using jquery –  softsdev Jul 9 at 14:20
add comment

1 Answer

This may helpful to you.

var errorArray = {};

errorArray["Slug"] = 'Some error message for the Slug text box';

$('#FormId').validate().showErrors(errorArray);

Link: Manually set unobtrusive validation error on a textbox

share|improve this answer
 
From [javascript] tag excerpt: "Unless a tag for a framework/library is also included, a pure JavaScript answer is expected." –  Pavlo Oct 2 at 11:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.