简体   繁体   中英

Display validation message for multiple fields of the same model property in the same view

I've got a model field like so:

[Required(ErrorMessage = "Required!")]
[Display(Name = "Some ID")]
[DataType(DataType.Text)]
[RegularExpression(@"SomeRegexHere"]
public string someId { get; set; }

On my view, I have a form for updating the model. Something like this:

<div class="form-group">
    @Html.LabelFor(model => model.someId, htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.someId, new { htmlAttributes = new { type = "number", @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.someId, "", new { @class = "text-danger" })
</div>

Say on this same view I can fill in this field in order to submit it to the database, but I may also fill in some other field to retrieve an entry in the database by this value. However, I'd like to apply the same validations to both fields. Without creating a dummy model attribute, can I display validation errors for both fields?

As I understand form you question, you need conditional validation . It is better to use third party validation provider for this porpose. I recommend MVC Foolproof Validation . Have a look on this and this as samples for conditional validation in foolproof.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM