MVC3 - 客户端验证

时间:2012-04-23 21:43:03

标签: asp.net-mvc-3 validation jquery-validate

即使textarea为空,我的表单也会发布到操作中。在post post上,我将其视为null。

此外,我有一个DI,存储库和服务架构。

我遵循了以下规则但仍然没有运气。

MVC3 client validation not working

这是我到目前为止所拥有的:

商家实体

namespace Intranet.BusinessEntities
{
    public partial class AnnualReportMessage
    {
        public string Message { get; set; }   
        public int AnnualReportYear { get; set; }
        public string Fice { get; set; }
    }
}

**Following is in Validations Folder**

using System.ComponentModel.DataAnnotations;

namespace Intranet.BusinessEntities
{
    [MetadataType(typeof(AnnualReportMessageMetaData))]
    public partial class AnnualReportMessage
    {
        private class AnnualReportMessageMetaData
        {
            [Required]
            public string Message { get; set; }
        }
    }
}

布局中引用了以下2

<script type="text/javascript" src="@Url.Script("jqueryMain/jquery.validate.js")"></script>
<script type="text/javascript" src="@Url.Script("jqueryMain/jquery.validate.unobtrusive.min.js")"></script>

Wen.config(全局,非特定区域)

<add key="ClientValidationEnabled" value="true"/>
        <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

页面上的HTML,我只需要“消息”,为什么我会看到其他字段的验证?

<form action="/Sales/AnnualReportNote" id="AnnualReportMessage" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="Q65zfJU+oSODE+qLj0Q0UpfaTId+ENEr+jucyhjWLbk1gnxY0QuTpu7R/lYOGtSxOYJwQkiPryCzgiTekyGikT/YrLQjF6hZXBhKkSF+UVzeAX2PuDrRoJR0pmWf5thL05LlAidHJtRcC3SHHGbxce5dqHSd1zIFpdQfQ3HPu10eUh55jMD4bn0cZeLReJ4P" />
    <input id="Fice" name="Fice" type="hidden" value="XXXXXX" />
    <input data-val="true" data-val-number="The field SetupYear must be a number." data-val-required="The SetupYear field is required." id="SetupYear" name="SetupYear" type="hidden" value="2012" />
    <input data-val="true" data-val-number="The field AnnualReportYear must be a number." data-val-required="The AnnualReportYear field is required." id="Message_AnnualReportYear" name="Message.AnnualReportYear" type="hidden" value="2012" />
    <input id="Message_Fice" name="Message.Fice" type="hidden" value="XXXXXX" />

    <textarea cols="70" data-val="true" data-val-required="The Message field is required." id="Message_Message" name="Message.Message" rows="12">
    </textarea>    

    <div class="distanceBottom"><span class="field-validation-valid" data-valmsg-for="Message.Message" data-valmsg-replace="true"></span></div>

    <input type="image" src="/App_Themes/Main/Images/ResponseAction/Buttons/btn_submit.gif" class="distanceTop" alt="Submit" id="SubmitButton" />
</form>

的JavaScript

formSubmit: function ($form, currentForm) {
        if ($form.validate().form()) {
            var $button = $("#" + AnnualReportSpecialEcMessage.enums.submitButtonId);

            jMessage("Processing request...", $button, true, false);
            $.ajax({
                cache: false,
                url: currentForm.action,
                type: currentForm.method,
                data: $form.serialize(),
                error: function (xhr, ajaxOptions, thrownError) {
                    jMessageError(xhr.responseText, $button, false, true);
                },
                success: function (result) {
                    if (result.IsError) {
                        jMessageError(result.Message, $button, false, true);
                    }
                    else {
                        jMessageOK(result.Message, $button, false, false);
                        jMessageHideInterval(3000); //hide after 3 seconds
                    }
                }
            });
        }
    }

我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:0)

我认为你需要这样做:

[MetadataType(typeof(AnnualReportMessage.AnnualReportMessageMetaData))] 

您是否有任何机会拥有不同的AnnualReportMessageMetaData类?

答案 1 :(得分:0)

使用它。它将删除mvc 3 razor中的默认验证方法。

 $(document).ready(function () {
   var form = $('#formId').get(0);
   $.removeData(form, 'validator');
 });

然后你的jquery验证码将起作用

答案 2 :(得分:0)

有问题的是jquery.validate.js。获得最新的或

替换

return $([]).add(this.currentForm.elements)
.filter(":input")

使用

return $(':input', this.currentForm)

完整的工作

elements: function() {
            var validator = this,
                rulesCache = {};

            // select all valid inputs inside the form (no submit or reset buttons)
            // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
            //return $([]).add(this.currentForm.elements)
            //.filter(":input")
            return $(':input', this.currentForm)
            .not(":submit, :reset, :image, [disabled]")
            .not( this.settings.ignore )
            .filter(function() {
                !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);

                // select only the first element for each name, and only those with rules specified
                if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
                    return false;

                rulesCache[this.name] = true;
                return true;
            });
        },