bulrush Posted May 25, 2010 Share Posted May 25, 2010 I have an <input type="text"> field. When the user exits the field I would like to validate the field, which is a date field. I'm sure I need to use Javascript to do this but I am new to Javascript and don't know how to integrate it with html. So, for example, if the user enters "5/16" I want to add the current year "/2010" to make "5/16/2010". This field also has a date picker, but if they don't use the date picker I want to validate what they do enter. Can someone possibly help me? Is there a good site on field validation using Javascript I could read? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/ Share on other sites More sharing options...
ScotDiddle Posted May 25, 2010 Share Posted May 25, 2010 bulrush, Here are a couple of options. The first example calls the javascript:dontDoThat() when the user clicks in the input field. The second example calls javascript:parseDate(this.value) when the user enters a date, the clicks outside of the input box ( This triggers the onBlur action ). Search Google for "Javascript Date Validation" for examples... Hope this helps. Scot L. Diddle, Richmond VA <?php Header("Cache-control: private, no-cache"); Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); Header("Pragma: no-cache"); ?> <html> <head> <script type="text/javascript"> function dontDoThat() { alert ('Input not allowed... Please use the Calendar control.'); document.getElementById('dontClickMe').value=''; } function parseDate(passedDate) { alert ('Date Parsing Logic for date: ' + passedDate + ' follows this alert...'); /* Check value, then if OK: */ document.getElementById('clickMe').value=passedDate; } </script> Pick a Date : <input type="input" size="45" value="Dont Click Here. Use Calander Control" id="dontClickMe" name="DontClickMe" onFocus="javascript:dontDoThat();"> <br /> <br /> Enter a Date : <input type="input" size="45" value="Input Date Here" id="clickMe" name="clickMe" onBlur="javascript:parseDate(this.value);" onFocus="this.value='';"> Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063234 Share on other sites More sharing options...
Psycho Posted May 25, 2010 Share Posted May 25, 2010 Here is a function from my personal library which I think will do as you ask. It takes a text input and attempts to parse it into a valid date. If it can, it returns the full date string in the format you want. Otherwise it returns false. The user can use just about any character as a delimiter (/, -, ., etc.) but will be returned using the separator you specify. See the examples in the description. //****************************************************************// // FUNCTION: fullDate(dateStr, [dateSep], [splitYr]) // // // // Takes a string variable that may be a 'partial' date format // // and converts it to a full format using the dateSep (defualt /) // // character. If only the last two digits of the year are given, // // the century (first 2 digits) will be determined by the splitYr // // value (default 29). Years greater than the splitYr will be set // // to the previous century, others to the current century. // // // // NOTE: The input may use any non alphanumeric character as the // // date separator. // // // // Examples: 1.3.2005 => 01-03-2005 // // 1/3/05 => 01-03-2005 // // 1*3 => 01-03-2005 // // 1+3+55 => 01-03-1955 // //****************************************************************// function fullDate(dateStr, dateSep, splitYr) { var datePattern = /^(\d{1,2})([^\w\s]{1})(\d{1,2})\2?(\d{2}|\d{4})?$/; var matchArray = dateStr.match(datePattern); //Check valid format if (matchArray == null) { return false; } //Set individual components of the date var month = (matchArray[1].length<2)?'0'+matchArray[1]:matchArray[1]; var day = (matchArray[3].length<2)?'0'+matchArray[3]:matchArray[3]; var year = matchArray[4]; //Set default values if not passed var dateSep = (dateSep) ? dateSep : '-'; var splitYr = (splitYr) ? splitYr : 29; //Convert year if empty or only 2 digits if (year.length<4) { var today = new Date(); var thisyear = today.getFullYear(); if (!year) { year = thisyear; } else { //Determine the century var century = Math.floor(thisyear/100); year = (year>splitYr) ? (century-1) + year : century + year; } } return month+dateSep+day+dateSep+year; } Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063245 Share on other sites More sharing options...
Psycho Posted May 25, 2010 Share Posted May 25, 2010 I forgot, that function only formats the date, but does not ensure it is a valid date (i.e. 5-50-5555 is a valid format). I have a related function to ensure the date is an actual date. //****************************************************************// // FUNCTION: isDate (dateStr) // // // // This function takes a string variable and verifies if it is a // // valid date or not. Dates must be in the format of mm-dd-yyyy // // or mm/dd/yyyy. It checks to make sure the month has the proper // // number of days, based on the month. The function returns true // // if a valid date, false if not. // // // // Day/Month must be 1 or 2 digits, Year must be 2 or 4 digits. // //****************************************************************// function isDate(dateStr) { var datePattern = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/ var matchArray = dateStr.match(datePattern); //Check valid format if (matchArray == null) { return false; } month = matchArray[1]; day = matchArray[3]; year = matchArray[5]; // check month range if (month < 1 || month > 12) { return false; } //Check day range if (day < 1 || day > 31) { return false; } //Check months with 30 days if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; } //Check Feb days if (month == 2) { var leapYr = (year%4 == 0 && (year%100 != 0 || year%400 == 0)); if (day > 29 || (day>28 && !leapYr)) { return false; } } return true; } Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063251 Share on other sites More sharing options...
bulrush Posted May 26, 2010 Author Share Posted May 26, 2010 Thank you, this is much appreciated. It would have taken me a good hour to research this and put it together, especially the February valid day part. Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063544 Share on other sites More sharing options...
ignace Posted May 26, 2010 Share Posted May 26, 2010 mjdamato never thought about publishing this as an open-source JS framework? Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063558 Share on other sites More sharing options...
Psycho Posted May 26, 2010 Share Posted May 26, 2010 I do have a few other related date functions as well. If I had the time I'd probably construct them all into a class. But, I just don't have the time - or the interest. Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063585 Share on other sites More sharing options...
bulrush Posted May 26, 2010 Author Share Posted May 26, 2010 This code works on my simpler screens. But it doesn't work on my entry screen. My entry screen has 10 identical rows, and one field of each row is a date field, and I'm using an array of date input fields (text boxes). Here is my Javascript first: <script type="text/javascript"> function valDate(fieldObj) { var arr=new Array(); var dt=new Date(); arr=fieldObj.split('/'); if (arr.length<3) //If missing year... { fieldObj.value.='/'.toString(d.GetFullYear()); //Append current year } return fieldObj; } //valDate </script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <script type="text/javascript"> //Javascript Comment $(document).ready(function() { var dt=new Date(); $("#txtDate[]").datepicker(); $("#txtDate[]").datepicker( "option", "minDate", new Date(2009, 1-1, 1) ); $("#txtDate[]").datepicker( "option", "maxDate", new Date(2010, 5-1, 31) ); }); </script> Now here is the PHP where I construct the input boxes. Take a look at txtDate[]. <?php $shownrows=0; for ($x=1; $x<=MAXMILERECS; $x++) { $shownrows++; $s='<tr>'; echo $s; $s='<td><input type="text" name="txtMid[]" value="" size="5" readonly />'; echo "$s\n"; $s='<td><input type="text" name="txtDate[]" id="txtDate[]" '. 'value="" size="8" onblur="valDate(this)" />'; //$s.='<div type="text" id="datepicker"></div>'; echo "$s\n"; $s='<td><input type="text" name="txtMiles[]" value="" size="6" />'; echo "$s\n"; $s='<td><input type="text" name="txtNote[]" value="" size="80" />'; echo "$s\n"; $s='</tr>'."\n"; echo "$s\n"; } echo '</table>'."\n"; // End parts. echo $buttons; //Command buttons ?> If the user enters "5/1" as the date, I want to append a slash and the current year. But my function valDate does not appear to be called. Any ideas? Does JS even work with an array of text input boxes? Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063623 Share on other sites More sharing options...
Psycho Posted May 26, 2010 Share Posted May 26, 2010 It has nothing to do with an array of fields. You code is just screwed up. There is NO WAY that code worked for a single field before you tested against an array of fields. There are numerous errors. besides that code will cause more problems than it would solve. Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063641 Share on other sites More sharing options...
Psycho Posted May 26, 2010 Share Posted May 26, 2010 Errors 1: You create a var called dt, but later try to refer to it as just d 2: You are trying to split the object and not the value arr = fieldObj.value.split('/'); 3: You are trying to concatenate text using the PHP operator '.' and not the JS operator '+' 4. The getFullYear property has a syntax error (should start with lower case 'g') 5. Your usage of toString() is completely wrong. Should be: dt.getFullYear().toString() 6. Why is the function returning the fieldObj when you don't use it? Although I think the function would be a bad solution, here is the fixed version function valDate(fieldObj) { var arr = new Array(); var dt = new Date(); arr = fieldObj.value.split('/'); if (arr.length<3) { fieldObj.value += '/' + dt.getFullYear().toString(); //Append current year } return; } //valDate Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063643 Share on other sites More sharing options...
bulrush Posted May 26, 2010 Author Share Posted May 26, 2010 Ok, so if there's an error in the Javascript, the Javascript won't run? Is that the problem? Because I put an alert() in my function valDate() and that alert didn't even show up. Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063649 Share on other sites More sharing options...
bulrush Posted May 26, 2010 Author Share Posted May 26, 2010 Hmm. I made the changes you showed above. This JS function valDate is not even getting called because my alert() function inside it is not firing. What am I doing wrong? Here's my code. <script type="text/javascript"> function valDate(fieldObj) { var arr=new Array(); var dt=new Date(); arr=fieldObj.value.split('/'); alert('Arr length='.arr.length); //DEBUG if (arr.length < 3) //If missing year... { fieldObj.value+='/' + dt.GetFullYear().toString(); //Append current year } else { fieldObj.value='yay!'; } return; } //valDate </script> My html now looks like this: $s='<td><input type="text" name="txtDate[]" id="txtDate[]" '. 'value="" size="8" onblur="valDate(this)" />'; //$s.='<div type="text" id="datepicker"></div>'; echo "$s\n"; Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063651 Share on other sites More sharing options...
Psycho Posted May 27, 2010 Share Posted May 27, 2010 Typically, one the first javascript error is encountered no other javascript will run - in that same thread. Did you even check the erro messages that were generated? OK, I was going to put some demeaning statement here because you again created the same problem I identified in promblem #3 above. But, I make that mistake as well when working between PHP and JavaScript. You are trying to concatenatin in JavaScript using the PHP method. This alert('Arr length='.arr.length); //DEBUG Should be this alert('Arr length='+arr.length); //DEBUG Quote Link to comment https://forums.phpfreaks.com/topic/202823-how-to-validate-field-when-user-exits-field/#findComment-1063881 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.