I use MVC3 model Validation and Unobtrusive for show validation and try to find some way to clone element and validation.
This is My View Code:
<div id="d1" class="Addable">
@Html.EditorFor(model => model.CellPhone)
@Html.ValidationMessageFor(model => model.CellPhone)
</div>
<input type"button" class="AddE" />
And HTML Dom is:
<div class="Addable" id="d1">
<input type="text" value="" name="CellPhone" id="CellPhone" data-val-required="Req."
data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true"
class="text-box single-line valid">
<span data-valmsg-replace="true" data-valmsg-for="CellPhone"
class="invalid-side-note field-validation-valid"></span>
</div>
So I use the following script to clone new one with change names like array names:
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable:first');
var TargetId = $(Target).attr('id');
var Count = $('.Addable#' + TargetId).size();
var CloneTarget = $(Target).clone();
CloneTarget.find('input').val('');
CloneTarget.insertAfter('.Addable:last');
var TargetName = $(Target).find('input').attr('name');
if (Count == 1) {
var CloneName = TargetName + '[1]';
TargetName = TargetName + '[0]';
$(Target).find('input').attr('name', TargetName);
$(Target).find('span[class|="field-validation"]').attr('data-valmsg-for', TargetName);
$(CloneTarget).find('input').attr('name', CloneName);
$(CloneTarget).find('span[class|="field-validation"]').attr('data-valmsg-for', CloneName);
} else {
var indx = TargetName.length - 3;
var CloneTargetName = TargetName.substring(0, indx);
CloneTargetName = CloneTargetName + '[' + Count + ']';
$(CloneTarget).find('input').attr('name', CloneTargetName);
$(CloneTarget).find('span[class|="field-validation"]').attr('data-valmsg-for', CloneTargetName);
}
});
After first clone the Dom is:
<div class="Addable" id="d1">
<input type="text" value="" name="CellPhone[0]" id="CellPhone" data-val-required="Req."
data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true"
class="text-box single-line valid">
<span data-valmsg-replace="true" data-valmsg-for="CellPhone[0]"
class="invalid-side-note field-validation-valid"></span>
</div>
<div class="Addable" id="d1">
<input type="text" value="" name="CellPhone[1]" id="CellPhone" data-val-required="Req."
data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true"
class="text-box single-line valid">
<span data-valmsg-replace="true" data-valmsg-for="CellPhone[1]"
class="invalid-side-note field-validation-valid"></span>
</div>
I change both validation span and input because every input will have own validation. but after clone the validation not worked at all. where is the problem? what is your suggestion?