日期:2014-05-16  浏览次数:20428 次

js表单校验(必录、日期数字校验)

//校验表单必录,每个必录的表单需要增加一个属性required='true'

function val(id){
    var selected = "#"+id+" :input[required='true']";
    var fields = $(selected);
    var flag = true;
    for(var i=0; i<fields.length; i++){
        if(fields[i].value.length == 0){
            flag = false;
            fields.eq(i).css("border-color","red");
        }
    }
    
    return flag;
}
?


//校验输入字数

function textCounter(field, maxlimit) {
    var trimed = field.value.replace(/^\s+|\s+$/g, '');
    if (trimed.length > maxlimit) {
        trimed =  trimed.substring(0, maxlimit);
        field.value = trimed;
    }
}
?



//短日期,形如 (2003-12-05)

function isDate(field){
    var str = field.value;
    var r = str.match(/^(\d{1,4})(-)(\d{1,2})(-)(\d{1,2})$/);
    if(r==null){
        alert("输入的数字不合法!");
        field.value = "";
        return false;
    }
    if(r[3]>12 || r[5] > 31){
        alert("输入的数字不合法!");
        field.value = "";
        return false;
    }
    return true;
}
?



//数字

function isNumber(field){
    var str = field.value;
    var r = str.match(/^(0|[1-9]\d*)$/);
    if(r==null){
        alert("输入的数字不合法!");
        field.value = "";
        return false;
    }
    return true;
}
?

//校验实数

function isBigDecimal(field,n){
    var str = field.value;
    var reg = "";
    if(n == null || n == ""){
        reg = "^[0-9]+(.[0-9]+)?)";
    }else{
        reg = "^[0-9]+(.[0-9]{1,"+n+"})?$";
    }
    var r = str.match(new RegExp(reg));
    if(r==null){
        alert("输入的数字不合法!");
        field.value = "";
        return false;
    }
    return true;

} 
?