MVC3简单的自定义验证

时间:2012-04-13 16:01:04

标签: asp.net-mvc-3 validation validationattribute

简单的自定义验证,

我的模型和自定义验证:

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>
}

1 个答案:

答案 0 :(得分: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方法是正常的。