ASP.NET MVC3. How to set validation to require one

2019-08-25 08:07发布

Here is my model:

public class RestoreRequestModel : IDataErrorInfo
{
    //true seems Value contains phone email otherwise
    public bool IsPhoneMode { get; set; }

    //Contains phone or email address.
    public string Value { get; set; }
}

And view:

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

    <label for="email">By Email</label>
    @Html.RadioButtonFor(x => x.IsPhoneMode, Constants.RESTORE_BY_EMAIL, new { id="email" })

    <label for="phone">By Phone</label>
    @Html.RadioButtonFor(x => x.IsPhoneMode, Constants.RESTORE_BY_PHONE, new { id = "phone" })

    <div class="editor-label">
        @Html.LabelFor(model => model.Value)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Value)
        @Html.ValidationMessageFor(model => model.Value)
    </div>

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

Is it possible to set validation depending on model.IsPhoneMode state? I can set validation by adding attributes to the model properties but there must be different validation conditions depending on RadioButton state.

2条回答
倾城 Initia
2楼-- · 2019-08-25 08:47

Nuget the FoolProof validation package. It is fully featured for situations like this.

查看更多
混吃等死
3楼-- · 2019-08-25 08:56

what you need is to implement your own attribute that makes a conditional requirement there are lots of blog posts that you can search about that topic or you can download Mvc.ValidationTookit

查看更多
登录 后发表回答