0
votes

I'm using jquery (unobtrusive) validation for MVC, and I have a field that is not a part of my model, so I'd rather not add it JUST to give it some data annotations.

And, all I need is to ensure that the value is equal to 100 ... I'd like this validated along with everything else.

I read this article: http://www.blinkingcaret.com/2016/03/23/manually-use-mvc-client-side-validation/

And, I added

data-val="true"

As well as

data-val-equalto="100"

But this didn't work.

<input type="text" name="smtotal" id="SMTotal" class="form-control " readonly="readonly" data-val="true"  data-val-equalto="100"/>
                        <span class="field-validation-valid" data-valmsg-for="smtotal" data-valmsg-replace="true">This must equal 100</span>
1

1 Answers

1
votes

There are a few issues. First, the data-val-equalto is where you put the error message that you want to display, not the value that you want to compare with. Also the equalto validator compares with a value in another field, not an arbitrary value like 100. You will have to provide the name of the other field in the data-val-equalto-other attribute.

To compare with a fixed value like 100, you can use the range validator and use the same value for the minimum and maximum, like this:

<input type="text" name="smtotal" id="SMTotal" class="form-control" readonly="readonly"
       data-val="true" data-val-range="This must equal 100"
       data-val-range-min="100" data-val-range-max="100" />
<span class="field-validation-valid" data-valmsg-for="smtotal"
      data-valmsg-replace="true"></span>

Notice that I didn't provide a message in the span, because the message is coming from the input. If you want to put the message in the span, then you have to set data-valmsg-replace to false.