Posted by: piman007 | 07-06-2007

JavaScript: ตรวจสอบการรับข้อมูลวันเดือนปี แบบไทยๆ

ถ้าไม่ป้อนข้อมูลอะไรลงไปมันก็ไม่ตรวจสอบนะครับ
format  dd/mm/yyyy
 
<form id="form1">
   <input type="text" name="datefield" id="datefield"  onBlur="checkDate(this);" />
</form>
<script language="JavaScript">
function  checkDate(fld){
    var entry = fld.value;
    if(entry==null) return;
    if(entry==”) return;
   
    var mo, day, yr;
    var reLong = /bd{1,2}[/-]d{1,2}[/-]d{4}b/;
    var valid = (reLong.test(entry));
    if (valid) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        day = parseInt(entry.substring(0, delim1), 10);
        mo = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = year_thai2eng(parseInt(entry.substring(delim2+1), 10));
        // handle two-digit year
        if (yr < 100) {
            var today = new Date();
            // get current century floor (e.g., 2000)
            var currCent = parseInt(today.getFullYear() / 100) * 100;
            // two digits up to this year + 15 expands to current century
            var threshold = (today.getFullYear() + 15) – currCent;
            if (yr > threshold) {
                yr += currCent – 100;
            } else {
                yr += currCent;
            }
        }
        var testDate = new Date(yr, mo-1, day);
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    // fill field with database-friendly format
                    fld.value = format(day) + "/" + format(mo) + "/" + year_eng2thai(yr);
                    return true;
                } else {
                    alert("There is a problem with the year entry.");
                }
            } else {
                alert("There is a problem with the month entry.");
            }
        } else {
            alert("There is a problem with the date entry.");
        }
    } else {
        alert("Incorrect date format. Enter as mm/dd/yyyy.");
  fld.value=”;
  fld.focus();
    }
}
function format(value){var str = ”+value;if(str.length==1){ return ‘0’+str;}else{return str;}}
function year_thai2eng(value){return value-543;}
function year_eng2thai(value){return value+543;}
</script>

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Google+ photo

You are commenting using your Google+ account. Log Out / เปลี่ยนแปลง )

Connecting to %s

หมวดหมู่

%d bloggers like this: