C#.NET表单正则验证

<asp:TextBox iv="l_10_n" id="txtOutfitAmount" runat="server" Width="200px"></asp:TextBox>
JS代码:
$(function () {
    $("input[iv]").blur(function () {
        var typevalue = $(this).attr("iv");
        var tvs = typevalue.split("_");
        if (tvs[0] == 'l') {
            var inputlength = getByteLen($.trim($(this).val()));
            if (inputlength == 0) {
                alert("此输入框不能为空");
            }
            if (inputlength > parseInt(tvs[1])) {
                alert("你输入的字符过长");
                $(this).val("");
            }
        }
        var type = tvs[2];
        //alert(type);
        if (type != undefined) {
            var bl = regular(type, $.trim($(this).val()));
            if (!bl) {
                alert("输入格式错误");
                $(this).val("");
            }
        }
    });
});
function regular(type, value) {
    var nreg = /^\d+$/; //整数
    var mreg = /^\w{3,}@\w+(\.\w+)+$/; //邮箱地址
    var ereg = /^[a-z,A-Z]+$/; //英语字符
    var creg = /^[\u4e00-\u9fa5]{0,}$/; //汉字
    var ireg = /^\d{17}[\d|X]|\d{15}$/; //身份证
    if (type == "c") {
        if (creg.test(value)) {
            return true;
        } else {
            return false;
        }
    }
    if (type == "n") {
        if (nreg.test(value)) {
            return true;
        } else {
        return false;
        }
    }
}
function getByteLen(val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/ig) != null) //全角
            len += 2;
        else
            len += 1;
    }
    return len;
}
后台验证方法:
if (!类名.validate("number", this.txtRemainAmount.Text.Trim()))
            {
                sb.Append("武器弹药数量格式错误!<br/>");
            }
验证代码:
public static bool validate(string type,string va)
        {
            Regex re = null;
            if (type == "number")//非负整数
            {
                re = new Regex(@"^\d+$");
                return re.IsMatch(va);
            }
            else if (type == "number1")//整数  
            {
                re = new Regex(@"^-?\d+$");
                return re.IsMatch(va);
            }
            else if (type == "email")//邮箱地址
            {
                re = new Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
                return re.IsMatch(va);
            }
            else if (type == "eng")//英文
            {
                re = new Regex(@"^[A-Za-z]+$");
                return re.IsMatch(va);
            }
            else if (type == "chi")//汉字
            {
                re = new Regex(@"^[\u4e00-\u9fa5]+$");
                return re.IsMatch(va);
            }
            else if (type == "ench")//英文汉字
            {
                re = new Regex(@"^([\u4e00-\u9fa5]+|[a-zA-Z]+)$");
                return re.IsMatch(va);
            }
            return false;
        }
posted @ 2013-05-17 16:19  BicycleBoy  阅读(286)  评论(0编辑  收藏  举报