how can i use dependency fields validation in MVC3

2019-08-26 18:04发布

I use the validation attribute on the fields of a class and has a requirement like that: if field 'a' is validate succeed then process the validation of field 'b' but if the field 'a' is not throw validation , ignore the validation of field 'b'.
does it feasible or i should think in other way?

public class myclass
{
[required]
public string a{get;set;}
[required]
public string b{get;set;]
}

i want: 1.if a pass the validate, then execute b 's validate 2.if a not pass the validate , then don't execute the b 's validate

2条回答
地球回转人心会变
2楼-- · 2019-08-26 18:45

Implement the IValidateableObject interface in your model to contain your custom validation logic. Since you cannot apply validation checks in the manner you've requested you need to resort to your own custom validation. I don't think Michael's suggestion )(although a good one) will work if you really need to say 'only if that is valid, validate something else' through attributes but this is done easily through this interface. However note this will be server side validation only unless you want to write your own client portion for this as well.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-26 19:00

Check out the MVC.ValidationToolkit

http://blogs.msdn.com/b/simonince/archive/2011/09/29/mvc-validationtookit-alpha-release-conditional-validation-with-mvc-3.aspx

It contains these two validations that will help you out.

  • RequiredIfAttribute. This attribute says “this field is required if some other field has value X”. It is used as [RequiredIf(“OtherField”, “TargetValue”)]
  • RequiredEmptyIfAttribute. This attribute says “this field must be empty if some other field has value X”. It is used as [RequiredEmptyIf(“OtherField”, “TargetValue”)]
查看更多
登录 后发表回答