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

前端 未结 2 1759
北海茫月
北海茫月 2021-02-20 02:34

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 q

2条回答
  •  耶瑟儿~
    2021-02-20 03:13

    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/

提交回复
热议问题