最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extending jQuery UI components ( Overriding jQuery Datepicker to prevent wrong input) - Stack Overflow

programmeradmin1浏览0评论

I am trying to extend the jQuery UI Datepicker for adding some validations.

I searched a lot in the internet, but I could not get any help. I found SO question jquery-datepicker-function-override, there is no way to modify the textinput behaviour, the datepicker ponent only supports onSelect event, which gets fired after the date is selected not when we change the date through textinput.

I have created fiddle to show the problem.

I have two date pickers, both showing wrong dates. In this case the date picker shows the current date of the system. First textinput contains 05-ddd-2014 and second one contains 05-march-2014, both are wrong dates.

Problem Demo


NOTE:

I know how to use the datepicker ponent, I want to support the validation on pressing / typing the keyboard. I need to extend the jQuery UI Datepicker ponent The question is not about date format. To simplify the question, I choose simple format (dd-M-yy (i.e 02-Feb-2014)). The question is all about handling the text input change event in case of wrong dates.


I am currently supporting only one input format dd-M-yy (i.e 02-Feb-2014).

When I am entering any wrong format directly in the text input (i.e 02-xxx-2014) , the date picker is showing the current date of the system ( current behaviour ).

Is there any way, I can validate the text entered in the text input and assign it to datepicker.

I tried using keydown event on textinput, but its not giving the correct key pressed sometimes, may be jQuery UI Datepicker is handling this event.

$('#datepicker').on("keydown", function(e) {
    var val = this.value;
    var ar = val.split("-");
    // dd - parse the date, do the required validation
    console.log( ar[0], isNaN(ar[0]) );
});

Is there any best practice to extend jQuery UI Datepicker or jQuery UI conmponents in general.

I am trying to extend the jQuery UI Datepicker for adding some validations.

I searched a lot in the internet, but I could not get any help. I found SO question jquery-datepicker-function-override, there is no way to modify the textinput behaviour, the datepicker ponent only supports onSelect event, which gets fired after the date is selected not when we change the date through textinput.

I have created fiddle to show the problem.

I have two date pickers, both showing wrong dates. In this case the date picker shows the current date of the system. First textinput contains 05-ddd-2014 and second one contains 05-march-2014, both are wrong dates.

Problem Demo


NOTE:

I know how to use the datepicker ponent, I want to support the validation on pressing / typing the keyboard. I need to extend the jQuery UI Datepicker ponent The question is not about date format. To simplify the question, I choose simple format (dd-M-yy (i.e 02-Feb-2014)). The question is all about handling the text input change event in case of wrong dates.


I am currently supporting only one input format dd-M-yy (i.e 02-Feb-2014).

When I am entering any wrong format directly in the text input (i.e 02-xxx-2014) , the date picker is showing the current date of the system ( current behaviour ).

Is there any way, I can validate the text entered in the text input and assign it to datepicker.

I tried using keydown event on textinput, but its not giving the correct key pressed sometimes, may be jQuery UI Datepicker is handling this event.

$('#datepicker').on("keydown", function(e) {
    var val = this.value;
    var ar = val.split("-");
    // dd - parse the date, do the required validation
    console.log( ar[0], isNaN(ar[0]) );
});

Is there any best practice to extend jQuery UI Datepicker or jQuery UI conmponents in general.

Share Improve this question edited Aug 11, 2017 at 15:46 ROMANIA_engineer 56.8k30 gold badges210 silver badges205 bronze badges asked Feb 10, 2014 at 10:10 user3278797user3278797 7
  • Would greatly appreciate if you can put your code up on JSFiddle or some other collaborative development site. It will help us figure out where exactly you are stuck. Just a thought. – Sachin Sharma Commented Feb 10, 2014 at 10:24
  • You can trap the change event of the input: stackoverflow./questions/11228689/… – Salman Arshad Commented Feb 10, 2014 at 10:24
  • One of the best-practice I can think on the top of my head is to simply disable any free-text-entry in date-picker box. – Sachin Sharma Commented Feb 10, 2014 at 11:31
  • @Sachin Sharma I need the user to be able to enter the date through textinput and datepicker ui too. – user3278797 Commented Feb 10, 2014 at 12:03
  • did you try $('#datepicker').on("change", function(e) { OR $('#datepicker').on("blur", function(e) { – Lab Commented Feb 12, 2014 at 12:35
 |  Show 2 more ments

2 Answers 2

Reset to default 2 +50

You can try using $.datepicker.parseDate( format, value, settings ) in the blur event, if the function returns and exception like

A number of exceptions may be thrown:

'Invalid arguments' if either format or value is null

'Missing number at position nn' if format indicated a numeric value that is not then found

'Unknown name at position nn' if format indicated day or month name that is not then found

'Unexpected literal at position nn' if format indicated a literal value that is not then found

If raised in the catch you can show your alert, and force a focus on the field.

Code:

$(".datepicker").datepicker({
    dateFormat: "dd-M-yy",
    showOtherMonths: true

}).on("blur", function (e) {
    var curDate = $(this).val();
    try {
        var r = $.datepicker.parseDate("dd-M-yy", curDate);
    } catch(e) {
        alert('Not VALID!');
        $(this).focus()
    }
});

Demo: http://jsfiddle/IrvinDominin/L6e6q/

UPDATE

You can build your own widget eg ui.datepicker2 usinf ui.widget.factory.

Create stateful jQuery plugins using the same abstraction as all jQuery UI widgets.

Using it you can extend the default and bind keydown and keyup events.

On keydown store the old value, and on keyup validate the input and if not valid, restore the old value.

Code:

$.widget("ui.datepicker2", {
    _init: function () {
        var $el = this.element;
        $el.datepicker(this.options);

        if (this.options && this.options.checkDate) {
            $el.on("keydown", function (e) {
                var curDate = $el.val();
                $el.attr("oldValue", curDate);
                return true;
            });
            $el.on("keyup", function (e) {
                var curDate = $el.val();
                try {
                    var r = $.datepicker.parseDate("dd-M-yy", curDate);
                } catch (ex) {
                    alert('Not VALID!');
                    $el.val($el.attr("oldValue"));
                    $el.focus();
                }
            });
        }
    }
});

$(".datepicker").datepicker2({
    dateFormat: "dd-M-yy",
    showOtherMonths: true,
    checkDate: true
})

Demo: http://jsfiddle/IrvinDominin/GLWT3/

Try this,

JsFiddle

$(function() {
    $( "#datepicker" ).datepicker({ dateFormat: "yy-M-dd" });

    $('#datepicker').on("keyup", function(e) {

    var val = this.value;
        if(!ValidateDate(val)){
        console.log("Date must be 2014-Mar-01 Format")
        }



});
  });


function ValidateDate(dtValue)
{
    console.log(dtValue)
var patt = new RegExp(/^20\d\d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(0[1-9]|[12][0-9]|3[01])$/);
var res = patt.test(dtValue);
return res;
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论