简体   繁体   中英

How to make a Textfield in a form (html, jsp) accept only dd/mm/yyyy format without clicking submit button

I have a field in a jsp form page which accepts "from date" and "to date".. Now I know the script code which can be used to validate this using a submit button.. But my field currently accepts 10 characters in any form....eg: 28/07/2000 or 2807//2/00 It accepts numbers and any number of /...

But I want the field to accept 2 nos followed by / then 2 nos followed by / and the year.. Also is it possible to provide onpage validation like if date is 31/01/2000...then once 31 is typed by the user second set of nos allowed should be 01,03,05,07...& so on... It should not allow 02,04..etc.. If date is 29/02/yyyy then yyyy should only leap years allowed... All this should be satisfied then only the cursor should move to other field & without refreshing the page...

Can this be achieved by ajax... Since I need validation after 2 nos are entered, If anyone has any idea I would appreciate if you could point me in the right direction...

By the way I currently use this code for date validation....

    function checkdate(frmdt,todt){
    var validformat=/^\d{2}\-\d{2}\-\d{4}$/
    var returnval=false
       if(!validformat.test(frmdt.value)){
           alert("Invalid frmdt");
           document.form.frmdt.value="";
   }
       else if(!validformat.test(todt.value)){
       alert("Invalid Date 2");
        document.form.todt.value="";
   }
        else{
        var start = document.form.frmdt.value;
         var end = document.form.todt.value;

         var stDate = new Date(start);
        var enDate = new Date(end);
       var compDate = enDate - stDate;

        if(compDate >= 0)
       return true;
         else
            {
          alert("End date should be greater than start date.");
          return false;
         }
           }
         }

You should have a look at the onkeyup event, if you bind your validation function to this event it will run every time a key is released. You could use the onkeydown event to store the current input value in a variable, and then the onkeyup event to run the validation. Then just edit the validation function to reset the input to the value stored in the variable when the key was pressed, if the validation is invalid. This way, as soon as a key is released, any invalid input would be undone.

It doesn't look like you are using jQuery at the moment (even though you have added the tag to your question). In case you want to use it you could use its .keyup() and .keydown() methods instead.

You won't need any AJAX for this unless you want to do the validation using server side code and send the result back asynchronously, but that seems overkill for this fairly simple requirement.

If I have understood correctly, then this solution should do what you have asked.

There are 3 states during input.

Red - definitely invalid

Yellow - partially valid

Green - definitely valid

HTML

<input id="date" type="text" maxlength="10" />

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global global */

(function (global) {
    "use strict";

    global.addEventListener("load", function onLoad() {
        global.removeEventListener("load", onLoad);

        document.getElementById("date").addEventListener("keyup", function (evt) {
            var target = evt.target,
                value = target.value,
                parts = value.split("/"),
                day = parseInt(parts[0], 10),
                month = parseInt(parts[1], 10) - 1,
                date = new Date(parseInt(parts[2], 10) || 1600, month, day),
                dateCheck = day === date.getDate() && month === date.getMonth(),
                finalCheck = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(18|19|20)\d\d$/.test(value) && dateCheck;

            if (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}$/.test(value) || (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}(0[1-9]|1[012])\/{0,1}$/.test(value) && dateCheck) || finalCheck) {
                if (finalCheck) {
                    target.style.backgroundColor = "green";
                } else {
                    target.style.backgroundColor = "yellow";
                }
            } else {
                target.style.backgroundColor = "red";
            }
        }, false);
    }, false);
}(window));

On jsfiddle

Update: to address the additional question in the comments below

Javascript

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global global */

(function (global) {
    "use strict";

    global.addEventListener("load", function onLoad() {
        global.removeEventListener("load", onLoad);

        document.getElementById("date").addEventListener("keyup", function (evt) {
            var target = evt.target,
                value = target.value,
                parts = value.split("/"),
                day = parseInt(parts[0], 10),
                month = parseInt(parts[1], 10) - 1,
                date = new Date(parseInt(parts[2], 10) || 1600, month, day),
                dateCheck = day === date.getDate() && month === date.getMonth(),
                finalCheck = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(18|19|20)\d\d$/.test(value) && dateCheck;

            if (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}$/.test(value) || (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}(0[1-9]|1[012])\/{0,1}$/.test(value) && dateCheck) || finalCheck) {
                if (finalCheck) {
                    target.style.backgroundColor = "green";
                } else {
                    target.style.backgroundColor = "yellow";
                }
            } else {
                target.style.backgroundColor = "red";
                if (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}(0[1-9]|1[012])\/{0,1}$/.test(value)) {
                    if (!dateCheck) {
                        alert("incorrect number of days for month");
                    }
                }
            }
        }, false);
    }, false);
}(window));

on jsfiddle

Update: and example of event listener functions that can be used to give compatability with older non-standard Internet Explorer

Use this for adding listeners

function addEvt(obj, type, fni) {
    if (obj.attachEvent) {
        obj['e' + type + fni] = fni;
        obj[type + fni] = function () {
            obj['e' + type + fni](window.event);
        };

        obj.attachEvent('on' + type, obj[type + fni]);
    } else {
        obj.addEventListener(type, fni, false);
    }
}

Use this for removing listeners

function removeEvt(obj, type, fni) {
    if (obj.detachEvent) {
        obj.detachEvent('on' + type, obj[type + fni]);
        obj[type + fni] = nul;
    } else {
        obj.removeEventListener(type, fni, false);
    }
}

In use

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global global */

(function (global) {
    "use strict";

    function addEvt(obj, type, fni) {
        if (obj.attachEvent) {
            obj['e' + type + fni] = fni;
            obj[type + fni] = function () {
                obj['e' + type + fni](window.event);
            };

            obj.attachEvent('on' + type, obj[type + fni]);
        } else {
            obj.addEventListener(type, fni, false);
        }
    }

    function removeEvt(obj, type, fni) {
        if (obj.detachEvent) {
            obj.detachEvent('on' + type, obj[type + fni]);
            obj[type + fni] = nul;
        } else {
            obj.removeEventListener(type, fni, false);
        }
    }

    addEvt(global, "load", function onLoad() {
        removeEvt(global, "load", onLoad);

        addEvt(document.getElementById("date"), "keyup", function (evt) {
            var target = evt.target,
                value = target.value,
                parts = value.split("/"),
                day = parseInt(parts[0], 10),
                month = parseInt(parts[1], 10) - 1,
                date = new Date(parseInt(parts[2], 10) || 1600, month, day),
                dateCheck = day === date.getDate() && month === date.getMonth(),
                finalCheck = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(18|19|20)\d\d$/.test(value) && dateCheck;

            if (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}$/.test(value) || (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}(0[1-9]|1[012])\/{0,1}$/.test(value) && dateCheck) || finalCheck) {
                if (finalCheck) {
                    target.style.backgroundColor = "green";
                } else {
                    target.style.backgroundColor = "yellow";
                }
            } else {
                target.style.backgroundColor = "red";
                if (/^(0[1-9]|[12][0-9]|3[01])\/{0,1}(0[1-9]|1[012])\/{0,1}$/.test(value)) {
                    if (!dateCheck) {
                        alert("incorrect number of days for month");
                    }
                }
            }
        });
    });
}(window));

On jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM