2

Friends ,I have a text box for date to be inserted by the user but i want it to allow user to insert only "dd" ,"mm" and "yyyy" values ,slashes(/)should be already present and as soon as the user inserts "dd" values the pointer should move directly behind the slash for "mm" value and on pressing backspace it should delete the "mm" or "dd "values not the slashes(/). Here is what i have tried but it does not give me the desired result-

function dateCheck(){

   var d_value=$("#pdate").val();
   if(d_value.length =="2" || d_value.length =="5")
   {

    $('#pdate').val($('#pdate').val()+"/");
   }

}

html code-

Date:<input type="text" name="p_date" id="pdate"  onkeydown="dateCheck()"  placeholder="DD/MM/YYYY" required />
  • 2
    using a datepicker will do good! – Pardeep Poria Jun 02 '16 at 11:01
  • Use `input type='date'` – Rayon Jun 02 '16 at 11:02
  • no actually i don't want to use that.. i am searching for something that can help me do this with text-box only @Poria –  Jun 02 '16 at 11:03
  • Try this http://www.jquerybyexample.net/2011/12/validate-date-using-jquery.html – Pardeep Poria Jun 02 '16 at 11:05
  • @Rayon ..Thanks that works fine...that was so damn easy.. –  Jun 02 '16 at 11:08
  • @Rayon..actually your solution gives me a substitute for the result i wanted..it is not exactly what i wanted..:) –  Jun 02 '16 at 11:11
  • Using input `type="date"`, be aware than there is no reliable way to display any specific date format. http://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format – A. Wolff Jun 02 '16 at 11:14
  • @Mneha, _A. Wolff_ is right. You can not really specify the expected format.. – Rayon Jun 02 '16 at 11:17
  • 1
    Also, `type="date"` is HTML5, so isn't natively [supported by older browsers](http://caniuse.com/#search=input%20type%3D%22date%22). – Dave Salomon Jun 02 '16 at 11:18
  • @A.Wolff,Rayon , i am getting the desired format,but is it possible to then convert this date into yyyy/mm/dd format so as to insert into MySQL database? –  Jun 02 '16 at 11:22
  • you can use this "^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\\d\\d)$" – Pardeep Pathania Jun 02 '16 at 11:24
  • @Mneha You get relevant format BUT this format should be relative to user localization, meaning each of your user and depending browser could get different format. Now using `input.value` should return the wire format, which is `yyyy-mm-dd`. But imho, you would have better to use a custom element/plugin to display and get a specific date format – A. Wolff Jun 02 '16 at 11:26
  • @A.Wolff...thanks ..i would rather go with using a jquery plugin to avoid future crisis.. –  Jun 02 '16 at 11:36

2 Answers2

0

There's probably plugins out there, but nobody's been too forthcoming with any. Here's something I've knocked up during my lunch break :).

It's not perfect, and could be improved with some tweaking. For example, highlighting multiple characters for deletion is a bit screwy, but hopefully it's not a bad starter for 10. Credit to this post for getting/setting the caret position. Also, it does allow invalid dates right now - 12/34/5678. It wouldn't be too difficult to sort that out. I might stick something on Git and finish it off when I get home.

I've hard-coded it for dd/mm/yyyy format, but, again, with improvments, it could use the user locale.

$.fn.textboxDatePicker = function() {

    var _getCaret = function(el) {
        if (el.selectionStart) {
          return el.selectionStart;
        } else if (document.selection) {
            el.focus();

            var r = document.selection.createRange();
            if (r == null) {
                return 0;
            }

            var re = el.createTextRange(), rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);

            return rc.text.length;
        }
        return 0;
    };

    var _setCaretPosition = function(elem, caretPos) {
        if (caretPos == 2 || caretPos == 5) {
            caretPos++;
        }
        if (elem != null) {
            if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.move('character', caretPos);
                range.select();
            } else {
                if (elem.selectionStart) {
                    elem.focus();
                    elem.setSelectionRange(caretPos, caretPos);
                }
                else elem.focus();
            }
        }
    };

    $(this).val('dd/mm/yyyy');

    $(this).on("keydown", function(e) {
        var keyCode = e.which || e.charCode || e.keyCode;
        var key = String.fromCharCode(keyCode);

        // arrows, home, end
        if ([35, 36].indexOf(keyCode) > -1) {
            return true;
        }

        if (keyCode == 37) {
            var newCaretPos = _getCaret(this) - 1;
            if ([2, 5].indexOf(newCaretPos) > -1) {
                _setCaretPosition(this, newCaretPos - 1);
                return false;
            }
            return true;
        }

        if (keyCode == 39) {
            var newCaretPos = _getCaret(this) + 1;
            if ([2, 5].indexOf(newCaretPos) > -1) {
                _setCaretPosition(this, newCaretPos + 1);
                return false;
            }
            return true;
        }

        // backspace
        if (keyCode == 8) {
            var text = this.value;
            var caret = _getCaret(this);
            if (caret == 3 || caret == 6) {
                caret = caret - 2;
            } else {
                caret--;
            }

            if (caret < 0) {
                return false;
            }

            var output = text.substring(0, caret);
            key = 'd';
            if (caret > 2) {
                key = 'm'
            };
            if (caret > 4) {
                key = 'y'
            };

            this.value = output + key + text.substring(caret + 1);
            _setCaretPosition(this, caret);
            return false;
        }

        if (/[0-9]/.test(key)) {
            var text = this.value;
            var caret = _getCaret(this);

            if (caret > 9) {
                return false;
            }

            var output = text.substring(0, caret);
            this.value = output + key + text.substring(caret + 1);
            _setCaretPosition(this, caret + 1);
        }
        return false;
    });
};

$('.date').textboxDatePicker();

UPDATE

Might be overthinking this. Could you just use 3 separate boxes and style them to look like one, with a little JS to sort out focusing between them?

https://jsfiddle.net/w9by2350/3/

MUCH cleaner!

Community
  • 1
  • 1
Dave Salomon
  • 3,287
  • 1
  • 17
  • 29
  • Thanks alot...this is exactly what i wanted..i appreciate your efforts..@Dave Salomon –  Jun 02 '16 at 12:10
  • Everything works fine ,but you cannot use backspace for deleting month and date in this solution..@Dave Salomon –  Jun 02 '16 at 13:13
  • 1
    True. https://jsfiddle.net/w9by2350/3/ works slghtly better still, but it's definitely not production-ready - would just need a bit of tweaking. Personally, I'd go for this solution rather than the first one I suggested, but, whatever works for you :). – Dave Salomon Jun 02 '16 at 13:18
  • This one is awesome...and much cleaner...thanks @Dave Salomon –  Jun 02 '16 at 13:22
  • i actually want to insert this value into mysql database ..can u guide me through the way to do this .. @Dave Salomon –  Jun 06 '16 at 13:06
  • @Mneha Which programming language are you using? To get the value from the input (for the second solution), you'll need to get each of the values from the textboxes and then just pass them to your server-side code (using AJAX, for example). https://jsfiddle.net/w9by2350/5/ shows getting each of the values and creating a JS Date object from them. – Dave Salomon Jun 06 '16 at 14:26
  • actually i don't want a button to pass those values to database file and i did try using oblur() on 'wrapper' but it does not seems to work and i tried posting the value through $.ajax method but nothing seems to help and i am using php and MySQL for the database. @Dave Salomon –  Jun 07 '16 at 06:24
-1

Try it

 function datecheck(){
     value=$(#input_id).val();
   if(value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/){
     return true;
   }else{
     alert("not valid format")
   }
 }
A. Jain
  • 167
  • 8