Extending jQuery UI components ( Overriding jQuery Datepicker to prevent wrong input)

烈酒焚心 提交于 2019-12-21 07:44:28

问题


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 component 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 component, I want to support the validation on pressing / typing the keyboard. I need to extend the jQuery UI Datepicker component 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.


回答1:


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.net/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.net/IrvinDominin/GLWT3/




回答2:


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;
}


来源:https://stackoverflow.com/questions/21674227/extending-jquery-ui-components-overriding-jquery-datepicker-to-prevent-wrong-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!