Question

simple custom validation,

my model and custom validation:

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

(Please see the inline comment above)

view:

@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>
}
Was it helpful?

Solution

Can't repro.

Model:

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

Controller:

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

View:

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

The IsValid method is always hit when the form is submitted. Also notice that I haven't enabled client side validation because I didn't include the jquery.validate.js and the jquery.validate.unobtrusive.js scripts. If you have included them and there's an error chances are that client side validation will prevent your form from even being submitted to the server in which case it would be normal for the IsValid method not being invoked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top