此代码正确验证:
@Html.LabelFor(m => m.FirstName, new { @class = "control-label col-md-2 required" })
<div class="col-md-4">
@Html.EditorFor(m => m.FirstName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FirstName)
</div>
此代码未正确验证:
@Html.LabelFor(model => model.User.FirstName, new { @class = "control-label col-md-3 required" })
<div class="col-md-8">
@Html.EditorFor(model => model.User.FirstName, new { @class = "form-control required" })
@Html.ValidationMessageFor(m => m.User.FirstName)
</div>
model.User来自第二个代码块,与第一个代码块中的“m”类型相同。
以下是模型中显示自定义验证器属性的块。
[DisplayName("First Name")]
[Required()]
[FirstLastName]
public string FirstName{ get; set; }
这是FirstLastName属性,适用于第一块代码,但不适用于第二块代码。
public class FirstLastNameAttribute : RegularExpressionAttribute
{
public FirstLastNameAttribute() :
base(@"^[A-Za-z0-9\.\-_\!\#\^\~ ]{1,31}(?<!\.)$")
{
ErrorMessageResourceName = "FirstLastNameErrorMessage";
ErrorMessageResourceType = typeof(Messages);
}
}
正确运行的第一块代码的HTML输出
<input class="input-validation-error text-box single-line form-control" data-val="true" data-val-regex="Allowed characters: a-Z, 0-9, .-_!#^~, and space. Cannot end with a period. Must be 1-32 characters." data-val-regex-pattern="^[A-Za-z0-9\.\-_\!\#\^\~ ]{1,31}(?<!\.)$" data-val-required="The First Name field is required." id="FirstName" name="FirstName" type="text" value="asdf." aria-required="true">
无法正常工作的第二块代码的HTML输出
<input type="text" value="" name="User.FirstName" id="User_FirstName" data-val-required="The First Name field is required." data-val-regex-pattern="^[A-Za-z0-9\.\-_\!\#\^\~ ]{1,31}(?<!\.)$" data-val-regex="Allowed characters: a-Z, 0-9, .-_!#^~, and space. Cannot end with a period. Must be 1-32 characters." data-val="true" class="text-box single-line form-control" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHklEQVQ4EaVTO26DQBD1ohQWaS2lg9JybZ+AK7hNwx2oIoVf4UPQ0Lj1FdKktevIpel8AKNUkDcWMxpgSaIEaTVv3sx7uztiTdu2s/98DywOw3Dued4Who/M2aIx5lZV1aEsy0+qiwHELyi+Ytl0PQ69SxAxkWIA4RMRTdNsKE59juMcuZd6xIAFeZ6fGCdJ8kY4y7KAuTRNGd7jyEBXsdOPE3a0QGPsniOnnYMO67LgSQN9T41F2QGrQRRFCwyzoIF2qyBuKKbcOgPXdVeY9rMWgNsjf9ccYesJhk3f5dYT1HX9gR0LLQR30TnjkUEcx2uIuS4RnI+aj6sJR0AM8AaumPaM/rRehyWhXqbFAA9kh3/8/NvHxAYGAsZ/il8IalkCLBfNVAAAAABJRU5ErkJggg=="); background-repeat: no-repeat; background-attachment: scroll; background-position: right center; cursor: auto;" aria-required="true">
嵌套对象验证有问题吗?有一个简单的工作吗?
答案 0 :(得分:0)
所以我弄清楚它为什么不起作用。
出于某种原因(我不明白为什么,所以如果有人可以解释请这样做,我会改变接受的答案)有括号&#34;()&#34;在必需属性打破它之后。删除括号后,一切正常。
InvalidOperationException
由于我正在使用的正则表达式,它也没有工作。它不喜欢反向查找[DisplayName("First Name")]
[Required]
[FirstLastName]
public string FirstName{ get; set; }
部分。所以删除它后,它就可以了。