ASP.NET MVC3:为什么我的自定义验证属性永远不起作用?

时间:2011-12-09 10:29:44

标签: javascript asp.net asp.net-mvc-3 validation models

基本上,我已经正确地遵循了不同的教程。现在,我的模型取自库文件(DLL),这不应该是一个问题,因为其他一切正常。

我的模特:

public class RoomBookingInsert
{

    public Int32 CostCentreNo { get; set; }
    public Int32 CustomerAccNo { get; set; }
    public Int32 RoomNo { get; set; }
    public Int32 ServiceCode { get; set; }
    [PriceValidation]
    public Decimal HourlyRate { get; set; }
    [DataType(DataType.Date)]
    [DateRange("2010/12/01", "2010/12/16")]
    public DateTime StartDate { get; set; }
}

属性被识别,因为它们相应地变为蓝色,并且自动完成检测它们。但是,当我发布我的表单时,它会接受任何内容。

我已将下面的代码包含在验证属性中,并且我认识到这是服务器端,因此发生在post命令上。

使用razor在asp.net mvc3中的表单:

@model MyLibrary.RoomBookingInsert

@{
    ViewBag.Title = "Temp";
}

<h2>Temp</h2>

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

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>RoomBookingInsert</legend>

        @Html.EditorForModel()
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

这是我的第一次价格验证(确保它永远不会消极)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

    public class PriceValidationAttribute : ValidationAttribute

    {
        private decimal minPrice = 0.00M;
        private decimal maxPrice = 100.00M;

            public PriceValidationAttribute()
            {
            }
            public override bool IsValid(object value)
            {
                decimal price = (decimal)value;
                if (price < this.minPrice || price > this.maxPrice)
                    return false;
                return true;
            }

    }

这是我的日期范围验证:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

    public class DateRangeAttribute : ValidationAttribute
    {
        private const string DateFormat = "yyyy/MM/dd";
        private const string DefaultErrorMessage =
               "'{0}' must be a date between {1:d} and {2:d}.";

        public DateTime MinDate { get; set; }
        public DateTime MaxDate { get; set; }

        public DateRangeAttribute(string minDate, string maxDate)
            : base(DefaultErrorMessage)
        {
            MinDate = ParseDate(minDate);
            MaxDate = ParseDate(maxDate);
        }

        public override bool IsValid(object value)
        {
            if (value == null || !(value is DateTime))
            {
                return true;
            }
            DateTime dateValue = (DateTime)value;
            return MinDate <= dateValue && dateValue <= MaxDate;
        }
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
                ErrorMessageString,
                name, MinDate, MaxDate);
        }

        private static DateTime ParseDate(string dateValue)
        {
            return DateTime.ParseExact(dateValue, DateFormat,
                 CultureInfo.InvariantCulture);
        }

}

3 个答案:

答案 0 :(得分:1)

页面不会自动验证。为了验证页面,您需要在控制器上执行的操作是这样的:

// Guessing your view is called Temp...
public class TempController : Controller
{
    // This method will create the view with the RoomBookingInsert model
    // NOTE: it has no HttpPost attribute
    public ActionResult Temp()
    {
         return View(new MyLibrary.RoomBookingInsert());
    }

    // This is the post back action method for your view
    // NOTE: this has an HttpPost attribute
    [HttpPost]
    public ActionResult Temp(MyLibrary.RoomBookingInsert model)
    {
        // Always start by checking the model state and if it is not valid
        // return the view with the original model
        if(!ModelState.IsValid)
        {
            return View(model);
        }

        // Rest of logic goes here
        ...
    }

}

答案 1 :(得分:1)

对于客户端验证,我没有看到,您已包含对jQuery本身的引用。你能仔细检查吗?

对于服务器验证,您应明确Validate它(如 user1039947 的答案中所述。

我建议你使用'Mvc.Futures',它有some of the validators implemented

答案 2 :(得分:0)

我在您的日期时间验证程序中发现的一个大问题是,当值为null或不是日期时,您返回true。它应该返回false。

十进制验证器中的另一个问题是,您不检查null值,也不检查它是否是有效小数。你只需将其打包,如果该值不是小数,则会抛出异常。