1

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?

Jtaylorapps
  • 5,680
  • 8
  • 40
  • 56

1 Answers1

0

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.

Community
  • 1
  • 1
Hadee
  • 1,392
  • 1
  • 14
  • 25
  • Nooot quite, I just need to apply the validations from some model attribute, e.g. ID, to multiple input boxes within the same view. This includes the need to be able to show validation errors for all of these inputs. – Jtaylorapps Aug 10 '16 at 14:02
  • That is the point!. Define conditional validation for "input boxes" based on "ID" value! – Hadee Aug 10 '16 at 20:49
  • The problem becomes showing the ValidationMessage for these other input boxes. I have no problems just creating multiple `EditorFor` the same field and all the validations apply. – Jtaylorapps Aug 11 '16 at 14:37