当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - How To: a required input on edit form, unchanged from default value, should be valid

问题描述:

Here's an example of one of several inputs on a Create form (note value is empty). In this context the validation (query.validate.unobtrusive) works as expected requiring the user to fill in the required fields in order to submit the form.

 <div class="form-group">

<div class="col-sm-offset-1 col-sm-8">

<input class="form-control" id="LegalName" name="LegalName" type="text"

value="" placeholder="Business Legal Name"

data-val-required="Legal Name is required." data-val="true" />

<span class="field-validation-valid" data-valmsg-for="LegalName"

data-valmsg-replace="true"></span>

</div>

</div>

For the Edit form I use the same html but pre-fill each input with its current value (in this case value="@Model.LegalName")

The problem is, even though each field is pre-filled with a value, the built-in validation prevents submitting the form, complaining that the required fields haven't been filled in.

The behavior I want is:

  1. Any input on the page may be left untouched with its current

    value

  2. Any input that the user changes must "pass" validation

    (e.g. nonempty, proper e-mail address)

For the Create case, the form validation feels "automatic" in that it just does the right thing. Is there a similarly "automatic" way to do this for the Edit case? Or do I have to do it manually (by coding the rules)?

Many Thanks,

Eric

网友答案:

Never mind... I'm an idiot today. The Form validation bit is working just fine. It's the Model binder that's got the issue... sigh.

That said, so it hasn't been a complete waste of time for you to read this there is a useful nugget here.

The Model used on this form contains, purely as a convenience, a class which has a couple of its own [Required] properties. Those properties aren't represented on the edit form so they were always coming back empty.

Thus, the moral of this story is: be careful using [Required] and similarly careful what you put in your View Models.

分享给朋友:
您可能感兴趣的文章:
随机阅读: