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>
<title>CSS Tooltip</title>
#nameError {display: none; color: red; font-weight: bold; font-size: 1.2em; margin-left: 10px; background-color: #FFDAB9;}
<legend>Student Information</legend>
<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.)
<button type="submit">OK</button>
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(); = "inline-block";

See a screenshot of the displayed validation message:

No comments:

Post a Comment