我的工具箱

1、数字输入框校验

// 绑定输入校验事件
function bindCheckEvent() {
    $('input[type="text"]').keyup([9, 2], filterKeyboardPress); // 屏蔽当前非法按键
    $('input[type="text"]').keypress([9, 2], filterKeyboardPress); // 屏蔽连续的非法按键
}

// 对于数字字段,过滤键盘输入
function filterKeyboardPress(event) {
    // 设置默认值
    var beforeDotNum, afterDotNum;
    if (typeof event.data == 'undefined') {
        beforeDotNum = 9;
        afterDotNum = 2;
    }
    else {
        beforeDotNum = event.data[0];
        afterDotNum = event.data[1];
    }

    var val = $(this).val();
    if (val == '') {
        return;
    }

    var reg1 = new RegExp('^\\d{' + (beforeDotNum + 1) + '}$');
    var reg2;
    if (afterDotNum == 0) {
        reg2 = new RegExp('^\\d{1,' + beforeDotNum + '}$');
    }
    else {
        // /^\d{1,9}\.?\d{0,2}$/
        reg2 = new RegExp('^\\d{1,' + beforeDotNum + '}\\.?\\d{0,' + afterDotNum + '}$');
    }
    if (isNaN(+val) || reg1.test(val) || !reg2.test(val)) {
        $(this).val(val.substr(0, val.length - 1));
    }
}
View Code

 2、日期处理

function formatDate(date, pattern) {
    if(typeof pattern == 'undefined'){
        pattern = 'yyyy\\MM\\dd';
    }

    var str = '';
    if (date instanceof Date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        if (month <= 9) {
            month = '0' + month;
        }
        var day = date.getDate();
        if (day <= 9) {
            day = '0' + day;
        }
        str = pattern.replace('yyyy', year).replace('MM', month).replace('dd', day);
    }

    return str;
}

function getDayNum(begin, end) {
    return (end - begin) / (24 * 60 * 60 * 1000);
}

function addDate(date, num) {
    return new Date((+date) + num * 24 * 60 * 60 * 1000);
}
View Code

 

posted @ 2016-09-09 10:42  Matt_Cheng  阅读(161)  评论(0编辑  收藏  举报