Forum Moderators: open
So, I'd like to check the following four text fields
BirthDate
StartDate
EndDate
DeathDate
Here is the current, working script for one field:
<script type="text/javascript">
/*In this example the date field is named:
BirthDate
The onBlur javascript event is triggered by:
checkdateBD()
*/
function checkdateBD(){
//window.onerror=null // for all other strange errors
var err=0
var psj=0;
var fff = document.forms[0];
a=fff.BirthDate.value
if (a.length!= 10) err=1
b = a.substring(0, 2)// month
c = a.substring(2, 3)// '/'
d = a.substring(3, 5)// day
e = a.substring(5, 6)// '/'
f = a.substring(6, 10)// year
//basic error checking
if (b<1 ¦¦ b>12) err = 1
if (c!= '/') err = 1
if (d<1 ¦¦ d>31) err = 1
if (e!= '/') err = 1
if (f<1899 ¦¦ f>2006) err = 1
//advanced error checking
// months with 30 days
if (b==4 ¦¦ b==6 ¦¦ b==9 ¦¦ b==11){
if (d==31) err=1
}
// february, leap year
if (b==2){
// feb
var g=parseInt(f/4)
if (isNaN(g)) {
err=1
}
if (d>29) err=1
if (d==29 && ((f/4)!=parseInt(f/4))) err=1
}
if (err==1){
alert('The date is an invalid (or out of range) format - \nMM/DD/YYYY is the correct format, please re-enter in your date.');
fff.BirthDate.value = ""
fff.BirthDate.focus()
}
}
</script>
And, withing the page itself here is what calls the script:
<p>
<input name="BirthDate" type="text" id="BirthDate" size="12" maxlength="12" onBlur="checkdateBD()">
Birthdate Checker
</p>
Any help would be appreciated! Thanks In Advance!
Crash
function checkdateBD(){
.....
var fff = document.forms[0];
a=fff.BirthDate.value
Now, suppose that instead of referencing the form objectfrom WITHIN the function, you simply PASS the form object to the function?
function checkdateBD(obj){
...
a=obj.value; // Don't need fff for this now
object_name=obj.name;
....
if (err==1) { alert('The '+object_name+' date is invalid'); }
Note I've assigned the object name to a variable so the user can make sense out of the alert. For this to work, you need to NOT use spaces in your form object names, and they cannot begin with a number:
<input type="text" name="birth_date" onBlur="checkdateBD(this);" value="">
<input type="text" name="other_date" onBlur="checkdateBD(this);" value="">
The "this" keyword refers to the current object and passes all of it's attributes. Thus you can pass the form object name, value, ID, style, anything, and it applies to all page objects, not just forms.
You can further clarify your alert by removing the underscore from the object's name if you want, search for regexps or replace functions.
As with all inherited things, there comes a time to get your hands dirty. Your time has come, best of luck! :-)