• [转]MVC+JQuery validate实现用户输入验证


    本文转自:http://www.cnblogs.com/ahui/archive/2010/10/08/1845677.html

    MVC服务器端:

    1.在controller中验证用户输入,如果验证失败,执行

    ModelState.AddModelError("LoginName", Resource.LoginName + Resource.WordSpace + Resource.CanNotBeBlank);

    2.在View视图某一个地方放置

    <%=Html.ValidationSummary()%>

    JS客户端:

    1.引放相应的JS文件

    <script src="/Js/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="/Js/jquery.validate.js" type="text/javascript"></script>

    2.在View视图某一个地方放置

    <label id="messageBox"></label>

    3.以常规的submit()方式提交,在页面最下面加入以下JS代码

     $(function() {
            $("#form1").validate({
                rules: {
                    LoginName: { required: true, regex: "^[0-9]+$" }
                },
                messages: {
                    LoginName: "<%=Resource.LoginName + Resource.WordSpace + Resource.CanNotBeBlank%>"
                },
                errorLabelContainer: "#messageBox",
                wrapper: "li"
            });
        });

     4.以Ajax方式提交到服务器的,JS代码要改为:

    var validate = null;
    var opts = {
        rules: {
            LoginName: { required: true, regex: "^[a-zA-Z][a-zA-Z0-9._-]{3,20}$" }
        },
        messages: {
            LoginName: "请输入正确的登陆名"
        },
        errorLabelContainer: "#messageBox",
        wrapper: "li"
    };
    
    function checkForm() {
        var b = validate.checkForm();
        validate.showErrors();
        return b;
    }
    
    $(function () {
        validate = $("#form1").validate(opts);
    });
    
    function SaveUser() {
        if (!checkForm()) {
            return;
        }
        //...........
    }

    要支持regex方式的验证,请在jquery.validate.js加入:

    // 正则表达式
    $.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            var check = false;
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
    );

    以上代码已实现双语化提示

    其它常用的验证方式有:

    required, remote, minlength, maxlength, rangelength, min, max, range, email, url, date, dateISO, number, digits, creditcard, accept, equalTo等

    可参见:

    http://docs.jquery.com/Plugins/Validation/validate

  • 相关阅读:
    CSZ CMS 1.2.7 xss分析与复现
    蚁剑改造过WAF系列(一)
    代理池
    二维码劫持案例分析
    入门KKCMS代码审计
    Xposed+XServer无需脱壳抓取加密包
    通达OA前台任意用户登录分析
    ATutor学习内容管理系统任意文件上传漏洞(CVE-2019-12169)分析
    调试System.AggregateException-即使在异步代码中也是如此
    关于System.Exception
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6410047.html
Copyright © 2020-2023  润新知