-1

I have this model:

public class TutorialBindingModel
{
    [Required]
    [RegularExpression(@"[A-Za-z0-9\ \-_]+", ErrorMessage = "You are using invalid characters")]
    [StringLength(128, ErrorMessage = "The {0} must be max 128 characters long.")]
    public string Title { get; set; }

    public List<SampleBindingModel> Samples { get; set; }
}

public class SampleBindingModel
{
    [Required]
    [StringLength(64, ErrorMessage = "The {0} must be max 64 characters long.")]
    [RegularExpression(@"[A-Za-z0-9\ \-_]+", ErrorMessage = "You are using invalid characters")]
    public string Name { get; set; }

    [Required]
    [StringLength(512, ErrorMessage = "The {0} must be max 64 characters long.")]
    [RegularExpression(@"[A-Za-z0-9\ \-_]+", ErrorMessage = "You are using invalid characters")]
    public string Description { get; set; }

}

When I fill tutorial there is a button which creates new sample form with suited fields. Sample form is partial view with model SampleBindingModel so I just put asp-for on field and change name on Samples[0].Name for example. And I get correct markup where fields of nested model have validation attributes in html:

<input class="item" name="Samples[0].Name" placeholder="Text" type="text" data-val="true" data-val-length="The Name must be max 64 characters long." data-val-length-max="64" data-val-regex="You are using invalid characters" data-val-regex-pattern="[A-Za-z0-9\ \-_]+"
  data-val-required="The Name field is required." id="Name" value="">
<span data-valmsg-for="Samples[0].Name" class="field-validation-valid" data-valmsg-replace="true"></span>

But the issues is that I can't validate this sample form. Main model is validated correctly but not the nested one. I think it's because I create sample form dynamically and I need to set validator on this form but I can't think how to do that

Sparky
  • 98,165
  • 25
  • 199
  • 285
Artyom
  • 654
  • 2
  • 7
  • 16

1 Answers1

2

The solution is simple. The issue was that when I create a new sample using jquery validator doesn't know about new fields so I removed validator and initialized it again on the sample creating

$("form").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
Artyom
  • 654
  • 2
  • 7
  • 16