HTML5中custom data-*特性与asp.net mvc 3 表单验证

 

      前面一篇文章我们介绍了HTML5中custom data-*特性,在Asp.net MVC Web App中原来我们对表单有验证,需要写这个js与Jquery Validation 插件配合, 回顾一下,看下面的代码:

   <!DOCTYPE html>
<html>
<head>
    <title>LoginWithModel</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.pack.js"
        type="text/javascript"></script>
 </head>
<body>
    <form action="/Security/LoginWithModel" method="post">  <table>
            <tr>
                <td>
                    <label for="UserName">User name</label>
                </td>
                <td>
                    <input id="UserName" name="UserName" type="text" value="" />
                    
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Email">Email address</label>
                </td>
                <td>
                    <input id="Email" name="Email" type="text" value="" />
                    
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Password">Password</label>
                </td>
                <td>
                    <input id="Password" name="Password" type="password" />
                    
                </td>
            </tr>
            <tr>
                <td>
                    <label for="ConfirmPassword">Confirm password</label>
                </td>
                <td>
                    <input id="ConfirmPassword" name="ConfirmPassword" type="password" />
                    
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" />
</form>    <script src="../../Scripts/MyformValidatation.js" type="text/javascript"></script>
</body>
</html>

JS 通常像这样:

$(document).ready(function () {

    $.validator.addMethod('Email', function (value) {
        return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
    }, 'Please enter correct email.');


    $("form").validate({
        rules: {
            UserName: { required: true },
            Email: { required: true, Email: true },
            Password: { required: true, range: [6, 12] },
            ConfirmPassword: { required: true, equalTo: "#Password" }
        }
            , messages: {
                UserName: { required: "Please enter UserName" },
                Email: { required: "Please enter Email", Email: "Please enter corret email" },
                Password: { required: "Please enter Password", range: "must be at least 6 characters long." },
                ConfirmPassword: { required: "Please enter confirm password." }
            }
                , wrapper: "p",
        errorPlacement: function (error, element) {
            if (error != null) {
                error.insertAfter(element);

            }
        }
    })
});

接下来我们在Asp.net MVC 3 web 中,启用Unobtrusive JavaScript来帮做验证,我们只需在Web.config设置
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

View, 先引用jquery.validate.unobtrusive.min.js,接着是这样的:

@model Mvc3App.Models.RegisterModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>LoginWithModel</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.pack.js"
        type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"
        type="text/javascript"></script>
</head>
<body>
    @Html.ValidationSummary("Errors have occurred:")
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td>
                    @Html.LabelFor(m => m.UserName)
                </td>
                <td>
                    @Html.TextBoxFor(i => i.UserName)
                    @Html.ValidationMessageFor(i => i.UserName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(m => m.Email)
                </td>
                <td>
                    @Html.TextBoxFor(i => i.Email)
                    @Html.ValidationMessageFor(i => i.Email)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(m => m.Password)
                </td>
                <td>
                    @Html.PasswordFor(i => i.Password)
                    @Html.ValidationMessageFor(i => i.Password)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(m => m.ConfirmPassword)
                </td>
                <td>
                    @Html.PasswordFor(i => i.ConfirmPassword)
                    @Html.ValidationMessageFor(i => i.ConfirmPassword)
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" />
    }

</body>
</html>

Model类, 注意上面使用是System.ComponentModel.DataAnnotations特性。

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    [RegularExpression("^[A-Za-z0-9]+$",ErrorMessage="Please correct format user name.")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Please correct format Email.")]
    public string Email { get; set; }

    [Required]
    [StringLength(12, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

这时最后render出来html,你有看到那些验证规则都出来了:

   <!DOCTYPE html>
<html>
<head>
    <title>LoginWithModel</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.pack.js"
        type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"
        type="text/javascript"></script>
</head>
<body>
    
<form action="/Security/LoginWithModel" method="post">        <table>
            <tr>
                <td>
                    <label for="UserName">User name</label>
                </td>
                <td>
                    <input data-val="true" data-val-regex="Please correct format user name." data-val-regex-pattern="^[A-Za-z0-9]+$" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />
                    <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Email">Email address</label>
                </td>
                <td>
                    <input data-val="true" data-val-regex="Please correct format Email." data-val-regex-pattern="^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" data-val-required="The Email address field is required." id="Email" name="Email" type="text" value="" />
                    <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Password">Password</label>
                </td>
                <td>
                    <input data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-length-max="12" data-val-length-min="6" data-val-required="The Password field is required." id="Password" name="Password" type="password" />
                    <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="ConfirmPassword">Confirm password</label>
                </td>
                <td>
                    <input data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="ConfirmPassword" name="ConfirmPassword" type="password" />
                    <span class="field-validation-valid" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true"></span>
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" />
</form>
</body>
</html>
有注意到上面的html中,有加入相应data-*特性。这就是ASP.NET MVC 3 特性之一,注意这里必须使用BeginForm才能生成它们。最后我们能实现相同的验证效果,而我们不需要单独写JS了。别需要注意是,如果引入jquery.validate.unobtrusive相关js, 再其它地方使用  $("form").validate() 时,则不会生效。原因是jquery.validate.unobtrusive提前注册validate方法,它会与你自已定义冲突.
如果你想看看有哪个内在验证规则,可以运行下面的html:
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Validate Unobtrusive demo</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js"
        type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"
        type="text/javascript"></script>
    <style type="text/css">
        body, input
        {
            font-size: 9pt;
        }
        .input-validation-error
        {
            border: 1px solid #ff0000;
        }
        .input-validation-valid
        {
            border: 1px solid #00ff00;
        }
        .field-validation-error
        {
            color: #ff0000;
        }
        .field-validation-valid
        {
            display: none;
        }
        .validation-summary-errors
        {
            font-weight: bold;
            color: #ff0000;
        }
        .validation-summary-valid
        {
            display: none;
        }
    </style>
</head>
<body>
    <form id="form1" method="get">
    <div data-valmsg-summary="true">
        <ul>
        </ul>
    </div>
    <div>
        <input type="text" id="tReq" name="tReq" data-val="true" data-val-required="requried" />
        <span data-valmsg-for="tReq"></span>
    </div>
    <div>
        <input type="text" id="tAccept" name="tAccept" value="a.doc" data-val="true" data-val-accept="name must be .jpg、.gif or .png"
            data-val-accept-exts="jpg|gif|png" />
        <span data-valmsg-for="tAccept"></span>
    </div>
    <div>
        <input type="text" id="tRegex" name="tRegex" value="123-ABC@" data-val="true" data-val-regex="Format as 999-999"
            data-val-regex-pattern="[0-9A-Z]{3}-[0-9A-Z]{3}" />
        <span data-valmsg-for="tRegex"></span>
    </div>
    <div>
        <input type="text" id="tDigit" name="tDigit" value="-1234" data-val="true" data-val-digits="should be digital" />
        <span data-valmsg-for="tDigit"></span>
    </div>
    <div>
        <input type="text" id="tNum" name="tNum" value="-1,234.56A" data-val="true" data-val-number="should be number" />
        <span data-valmsg-for="tNum"></span>
    </div>
    <div>
        <input type="text" id="tDate" name="tDate" value="X/01/X2000" data-val="true" data-val-date="should be digital Date" />
        <span data-valmsg-for="tDate"></span>
    </div>
    <div>
        <input type="text" id="tEmail" name="tEmail" value="jeffrey @mail.com" data-val="true"
            data-val-email="should be Email" />
        <span data-valmsg-for="tEmail"></span>
    </div>
    <div>
        <input type="text" id="tUrl" name="tUrl" value="http:// blog.darkthread.net" data-val="true"
            data-val-url="should be url" />
        <span data-valmsg-for="tUrl"></span>
    </div>
    <div>
        <input type="text" id="tLen" name="tLen" value="TTT" data-val="true" data-val-length="Length  from 4 to 8"
            data-val-length-min="4" data-val-length-max="8" />
        <span data-valmsg-for="tLen"></span>
    </div>
    <div>
        <input type="text" id="tRange" name="tRange" value="5" data-val="true" data-val-range="range from 10 to100"
            data-val-range-min="10" data-val-range-max="100" />
        <span data-valmsg-for="tRange"></span>
    </div>
    <div>
        <input type="text" id="tEq" name="tEq" value="99" data-val="true" data-val-equalto="same as above value"
            data-val-equalto-other="tRange" />
        <span data-valmsg-for="tEq"></span>
    </div>
    <div>
        <input type="submit" id="send" value="Send" />
    </form>
</body>
</html>

Asp.net MVC 3 中 Unobtrusive JavaScript, 简化我们Web开发,提高了开发效率。
希望对您Web开发有帮助。
您可能感兴趣的文章:
 
Html 5中自定义data-*特性
Asp.net MVC中表单验证

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。

你可能感兴趣的:(HTML5中custom data-*特性与asp.net mvc 3 表单验证)