logo

JavaScript String isFormat Prototype

I'm under the distinct impression that I need to restore your faith in me after yesterday's debacle and so today I will and share something more useful. Here's a way in JavaScript to add a validation method to all string objects. All you have to do is add the following function to your library:

String.prototype.isFormat = function ( sType ) {
var undef;
var aTypes = new Array();
aTypes['time'] = /^[0-2]?\d:[0-5]{1}\d/;
aTypes['date'] = /^[0-3]?\d\/[0-1]?\d\/\d{4}/;
aTypes['@unique'] = /^\D{4}-[\d|\D]{6}/;
if ( isUndefined( aTypes[ sType ] ) ) {
return sType.test( this );
} else {
return aTypes[ sType ].test( this );
}
}

Then when you're validating fields you can make it a little simpler. Here's a function that validates three fields. Note that in the last field we are using a custom written Regular Expression.

function validateForm( frm ) {
if( !frm.DateField.value.isFormat("date") )
alert('You need to enter a date in this field!');
if( !frm.TimeField.value.isFormat("time") )
alert('You need to enter a time in this field!');
if( !frm.PhoneNumber.value.isFormat(/^\d{9}$/ ) )
alert('You need to enter a number of 9 digits!');
}

Okay, so it doesn't make it that much simpler but it's a good way of demonstrating the use of JavaScript's Prototype object. Am I let off now?

Comments

  1. Doeesn't make it that much simpler? Are you kidding?

    Even though I already use lots of regexp in my validation functions, this is much simpler. Thanks for stretching my brain ;-)

    BTW, have you really been using this or it it just a quick proof-of-concept for you?

    • avatar
    • Jake
    • Fri 22 Nov 2002 16:06

    Glad you like it. I do actually use it and can claim it all as my own idea. Not many JavaScript functions that I can lay this claim on ;o)

    • avatar
    • RK
    • Wed 28 Jan 2009 05:12 AM

    Thank you. Excellent work.

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:


About This Page

Written by Jake Howlett on Fri 22 Nov 2002

Share This Page

# ( ) '

Comments

The most recent comments added:

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

More Content