我有这个模型:
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; }
}
当我填写教程时,有一个按钮可以创建带有合适字段的新示例表单。样本表单是模型为SampleBindingModel
的局部视图,因此我仅将asp-for
放在字段上并在name
上更改Samples[0].Name
。而且我得到正确的标记,其中嵌套模型的字段在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>
但是问题是我无法验证此样本表单。正确验证了主模型,但未验证嵌套模型。我认为这是因为我动态创建示例表单,并且需要在此表单上设置验证器,但我不认为该怎么做
答案 0 :(得分:0)
解决方案很简单。问题是,当我使用jquery验证器创建新示例时,不知道新字段,因此我删除了验证器,并在创建示例时再次对其进行了初始化
$("form").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");