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?
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?
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)
Thank you. Excellent work.