Nik*_*las 21 validation asp.net-mvc data-annotations
有没有办法使数据注释有条件?我有一张桌子Party,可以存放组织和人员.如果我要添加一个组织,我不希望需要字段姓氏,但只有在我添加一个人时才需要.
public class Party
{
[Required(ErrorMessage = "{0} is missing")]
[DisplayName("Your surname")]
public object surname { get; set; }
[DisplayName("Type")]
public object party_type { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
我想要一个条件所需的数据注释的条件,例如:
if (party_type=='P')then姓氏是必需的,否则姓氏可以是空的.
编辑
如果我必须将此验证移动到控制器,我该怎么做?如何从那里触发相同的错误消息?
tva*_*son 32
您可以使模型继承自IValidatableObject,然后将自定义逻辑放入Validate方法中.您还必须从属性中删除RequredAttribute.您将不得不编写一些自定义javascript来验证客户端上的此规则,因为Validate方法不会转换为不显眼的验证框架.注意我将属性更改为字符串以避免强制转换.
此外,如果您从属性中获得其他验证错误,那么这些错误将首先触发并阻止运行Validate方法,因此只有在基于属性的验证正常时才会检测到这些错误.
public class Party : IValidatableObject
{
[DisplayName("Your surname")]
public string surname { get; set; }
[DisplayName("Type")]
public string party_type { get; set; }
...
public IEnumerable<ValidationResult> Validate( ValidationContext context )
{
if (party_type == "P" && string.IsNullOrWhitespace(surname))
{
yield return new ValidationResult("Surname is required unless the party is for an organization" );
}
}
}
Run Code Online (Sandbox Code Playgroud)
在客户端,您可以执行以下操作:
<script type="text/javascript">
$(function() {
var validator = $('form').validate();
validator.rules('add', {
'surname': {
required: {
depends: function(element) {
return $('[name=party_type]').val() == 'P';
}
},
messages: {
required: 'Surname is required unless the party is for an organization.'
}
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14515 次 |
| 最近记录: |