Friday, 4 October 2013

Automatic client-side validation using the HTML5 'pattern' attribute

The new "pattern" attribute defined in HTML5 facilitates automatic validation of a textbox value by allowing the developer to define a Regular Expression pattern for the field. On form submission, the input value is validated against the pattern, and if the validation fails, the browser highlights the field and shows an error message.
Let's see an example that illustrates all this:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pattern attribute example</title>
</head>
<body>
<form>
<label id="pincode">Pin Code:</label>
<!--"required" attribute makes input mandatory in an input element -->
<input type="text" id="pincode" name="pincode"
pattern="^[1-9][0-9]{5}$" required
title="A six digit number that doesn't begin with zero.">
<br /> <br />
<button type="submit">Submit</button>
</form>
</body>
</html>


Running the above code in the Google Chrome browser gives me the following screenshot:


Wednesday, 2 October 2013

JavaScript Slideshow

In this post, I will illustrate how to periodically change the image source of an 'img' element using JavaScript. This is a simple Slideshow, and doesn't show any animation in sliding in and sliding out of images. Images will be shown one after one at an interval of 3 seconds. Let's see the code now:



<!DOCTYPE html>
<html>
<head>
<title>JavaScript Slideshow</title>
</head>
<body>
<img >
<script>
var photos = ["file:///C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Lighthouse.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Koala.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Jellyfish.jpg"];
setInterval(changePhoto, 3000); //change image every 3 seconds
var imageElement = document.getElementsByTagName("img")[0];
imageElement.src = photos[0];
var arrayIndex = 0;
var arrayLength= photos.length;
function changePhoto() {
arrayIndex++;
if (arrayIndex === arrayLength) {
arrayIndex = 0;
}
imageElement.src = photos[arrayIndex];
}
</script>
</body>
</html>



Monday, 30 September 2013

Extending properties/methods of an existing class in JavaScript

In JavaScript, properties/methods of an existing class can be extended by using the 'prototype' property of that class. Let's see an example of how to add a function named 'isInt' to String class. This function, as is obvious from its name, tells whether the text content of the target String is a number or not.


<script>
if (String.prototype.isInt == null) {
String.prototype.isInt = function() {
var result = parseInt(this.valueOf());
return !isNaN(result);
}
}
var i = "27";
var j = "shyam";
var paraElement = document.getElementById("output");
paraElement.innerHTML = ("Is '27' an integer : " + i.isInt());
paraElement.innerHTML += (" <br > Is 'shyam' an integer : " + j.isInt());
</script>

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:

Showing tooltip for a DOM element using CSS.

Some websites show tooltips for input controls to help user enter the correct values. This not only provides for better user experience, but also potentially reduces the server network traffic as there are less chances of the failed validation at the server end, and the resultant transmission of error messages from the server to the user.

The question is how to show the tooltip to the user as a DOM element doesn't expose any property for tooltip? The answer lies in using CSS. Let's see an example of how it is done.





<!DOCTYPE html>
<html>
<head>
<title>CSS Tooltip</title>
<style>
div {position: relative;}
#nameTip {position: absolute; left: 20%; top: 8%;}
span {display: none;}
div:hover span{display: inline; color: green; background-color: yellow;}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Student Information</legend>
<div>
<label id="studentName">Student name:</label>
<input type="text" id="studentName">
<span id="nameTip">Minimum allowed length is 3, and max length is 12</span>
</div>
<div>
<label id="dob">Date of birth:</label>
<input type="text" id="dob">
<span id="dobTip">Date should be in the format like 2013-29-09</span>
</div>
<div>
<button type="submit">OK</button>
</div>
</fieldset>
</form>
</body>
</html>



See the screenshot below of the tooltip popped up (the mouse is not visible in the screenshot, and I don't know how to capture it):



PS: I later discovered that DOM Elements expose a attribute called "title", and setting the value of this attribute effectively works as a tooltip for that element.


Friday, 13 September 2013

Coloring alternate rows of a HTML table

A table containing large number of rows can be visually represented in a better way by coloring alternate rows in different (often contrasting) colors. The rows can be styled using the CSS selectors. Let's see an example of this:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Selecting Alternate Table Rows</title>
<style>
    table {border-collapse: collapse;}
    th, td {border: 1px solid gray; padding: 5px;}
    tr:nth-child(2n+2) {background: #E1F5A9;}
    tr:nth-child(2n+3) {background: #CEECF5;}
    tr:first-child{background: #F6CECE;}
    
</style>
</head>
<body>

<h1>CSS Table Row Selectors</h1>

<table>
    <tr>
        <td>Col 1</td> <td>Col 2</td> <td>Col 3</td>
    </tr>
    
    <tr>
        <td>One</td> <td>Two</td> <td>Three</td>
    </tr>
    
     <tr>
        <td>Asia</td> <td>Africa</td> <td>Europe</td>
    </tr>
    
     <tr>
        <td>Summer</td> <td>Winter</td> <td>Spring</td>
    </tr>
     
     <tr>
        <td>Cricket</td> <td>Football</td> <td>Tennis</td>
    </tr>
</table>

</body>
</html>

Here is the output:


Cancelling form submission through JavaScript

When doing client-side validation on a web form, there arises a need to cancel the form submission if the user has not provided the data as required by the host website. This can be easily accomplished by invoking the preventDefault method on the 'event' argument passed to the form's 'Submit' event-handler. An example will better illustrate it; so, here it goes:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Cancelling Form Submission</title>
<style>
    .error {border: 2px solid red;}
    div:last-child {margin-top: 10px;}
</style>
</head>
<body>

<form method="post" action="#">
     
   <div>
        <label for="name">Your name (atleast 3 characters long): </label>
        <input type="text" name="name" id="name" required />
   </div>
   
    <div>
        <button type="submit">OK</button>
    </div>
</form>

<script>
    
    var formElement = document.forms[0];
    formElement.addEventListener("submit", onFormSubmission, false);
    
    function onFormSubmission(e) {
        var textElement = document.getElementById("name");
        if (textElement.value.length < 3) {
            textElement.className = "error";
            e.preventDefault();
        }
    }     
    
</script> 

</body>

</html>

Some people could say that what I have written is nothing new, and is known for ages. They would be very true if they said so. However, my motive behind writing these posts is not to announce any path-breaking discoveries to the world, but to note down some of my learnings so as to reinforce it.