我的視圖模型中有2個文本字段text1和text2。我需要驗證是否輸入了text1,然後輸入text2,反之亦然。在視圖模型中的自定義驗證中如何實現這一點?在2個字段上的asp.net mvc驗證 - 其他輸入時必須存在
謝謝。
我的視圖模型中有2個文本字段text1和text2。我需要驗證是否輸入了text1,然後輸入text2,反之亦然。在視圖模型中的自定義驗證中如何實現這一點?在2個字段上的asp.net mvc驗證 - 其他輸入時必須存在
謝謝。
可以使用實現對服務器端驗證IValidatableObject
(從System.ComponentModel.DataAnnotations
命名空間)您的視圖模型:
public class AClass : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public string SecondName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if((!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)))
yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
}
}
現在,它使當然,如果Name和SecondName都設置了,或者null,那麼model是有效的,否則它不是。
您可以使用jQuery,像這樣:
$("input[x2]").hide();
$("input[x1]").keypress(function() {
var textValue = ("input[x1]").val();
if(textValue)
$("input[x2]").show();
})
如果你想使用數據註釋驗證和模型驗證屬性,你應該看看這個: 「attribute dependent on another field」
看MVC萬無一失驗證它確實有條件的驗證。在nuget上查找它或者http://foolproof.codeplex.com
僅供參考,我建議在使用驗證摘要時不要返回驗證結果中的字段。如果您返回驗證結果中的兩個字段,則驗證摘要將包含兩條消息,而不是預期的單條消息。 – 2015-03-31 17:22:05
你可以包含一些代碼來說明如何使用它來註釋類屬性嗎? – niico 2017-02-24 17:35:03