1

简单的自定义验证,

我的模型和自定义验证:

public class Registration
{
    [Required(ErrorMessage = "Date of Birth is required")]         
    [AgeV(18,ErrorMessage="You are not old enough to register")]
    public DateTime DateOfBirth { set; get; }
}

public class AgeVAttribute : ValidationAttribute
{
    private int _maxAge;

    public AgeVAttribute(int maxAge)
    {
        _maxAge = maxAge;
    }

    public override bool IsValid(object value)
    {
        return false;       <--- **this never gets executed.... what am I missing?**
    } 
}

(请参阅上面的内联评论)

看法:

@using (Html.BeginForm()) {
@Html.ValidationSummary("Errors")
<fieldset>
    <legend>Registration</legend>
    <div class="editor-label">
        @Html.LabelFor(model => model.DateOfBirth)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DateOfBirth)    
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}
4

1 回答 1

2

无法复现。

模型:

public class Registration
{
    [Required(ErrorMessage = "Date of Birth is required")]
    [AgeV(18, ErrorMessage = "You are not old enough to register")]
    public DateTime DateOfBirth { set; get; }
}

public class AgeVAttribute : ValidationAttribute
{
    private int _maxAge;

    public AgeVAttribute(int maxAge)
    {
        _maxAge = maxAge;
    }

    public override bool IsValid(object value)
    {
        return false;
    }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Registration
        {
            DateOfBirth = DateTime.Now.AddYears(-10)
        });
    }

    [HttpPost]
    public ActionResult Index(Registration model)
    {
        return View(model);
    }
}

看法:

@model Registration

@using (Html.BeginForm()) 
{
    @Html.ValidationSummary("Errors")
    <fieldset>
        <legend>Registration</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.DateOfBirth)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DateOfBirth)    
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

提交表单时始终会点击 IsValid 方法。另请注意,我没有启用客户端验证,因为我没有包含jquery.validate.jsjquery.validate.unobtrusive.js脚本。如果您已包含它们并且存在错误,则客户端验证可能会阻止您的表单甚至被提交到服务器,在这种情况下,不调用 IsValid 方法是正常的。

于 2012-04-13T16:10:23.383 回答