Monday, 30 September 2013

Displaying validation failed messages to user using JavaScript and CSS

We need to alert the user of the failed validation if he has entered wrong input values in a web form. The validation is done prior to the form submitted to the server (back-end), and the submission is cancelled if the validation fails. Let's see an example of how to do client-side validation, and show error message(s) on validation failure.


<!DOCTYPE html>
<html>
<head>
<title>CSS Tooltip</title>
<style>
#nameError {display: none; color: red; font-weight: bold; font-size: 1.2em; margin-left: 10px; background-color: #FFDAB9;}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Student Information</legend>
<div>
<label id="studentName">Student name:</label>
<input name="student">
<span id="nameError">Name not specified, or not of valid length.</span>
<br />
(Minimum allowed length is 3, and max allowed length is 12.)
</div>
<div>
<button type="submit">OK</button>
</div>
</fieldset>
</form>
<script>
var frm = document.forms[0];
frm.addEventListener("submit", onFormSubmit, false);
var nameField = document.getElementsByName("student")[0];
var errorElement = document.getElementById("nameError");
function onFormSubmit(e) {
if (nameField.value.length < 3 || nameField.value.length> 12) { //validation failed
e.preventDefault();
errorElement.style.display = "inline-block";
nameField.focus();
}
}
</script>
</body>
</html>

See a screenshot of the displayed validation message:

No comments:

Post a Comment