开发者

Custom DateTime validation in ASP .NET - MVC

I try to implement new validationrules in my MVC-Project but i wont become a validation-errormsg in my view. What is wrong with the code? I have googlet alot and thought i have done all right -.-

WebConfig:

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

Model:

public class Model1 : IValidatableObject
{
    [Required]
    [DisplayFormat(DataFormatString="{d:0}", ApplyFormatInEditMode=true)]
    public DateTime Wunschtermin { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Wunschtermin < DateTime.Now) yield return new ValidationResult("error1!", new[] { "Wunschtermin" });
        if (Wunschtermin.Date > DateTime.Today.AddYears(2)) yield return new ValidationResult("error2", new[] { "Wunschtermin" });
    }
    ...

View:

@model TestMvcApplication.Models.Model1

<h2>Create</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>
    ...
        <div class="editor-field">
            @Html.EditorFor(model 开发者_开发技巧=> model.Wunschtermin)
            @Html.ValidationMessageFor(model => model.Wunschtermin)
        </div>
    ...

Edit:

Maybe I can override the RangeAttribute and avoid the problem:

[Range (DateTime.Now, DateTime.Today.AddYears(2))]

usefull?


have solved it myself, the code in the Controler was wrong:

    [HttpPost]
    public ActionResult Create(FormCollection collection)

with a smal change:

    [HttpPost]
    public ActionResult Create(Model1 collection)

it works well :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜