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>