いくつかのプロパティに渡す必要があるカスタム検証属性があります。しかし、私の問題は、属性自体を適用するときに発生します。私はバックネットで学習しているので、 "より単純な"問題に悩まされがちです。私は既にプロパティを静的にしようとしましたが、それは私の見解の一部を混乱させました。私はこれにどのようにアプローチできますか?
属性:"静的でないフィールド、メソッド、またはプロパティにオブジェクト参照が必要です。 'RxCard.dataobjects.Pharmacy.Area.Get'"
public class MinimumPhoneDigits : ValidationAttribute
{
public string[] _properties;
public int _expectedsize;
public MinimumPhoneDigits(int expectedsize, params string[] properties)
{
ErrorMessage = "Not the expected size!";
_properties = properties;
_expectedsize = expectedsize;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return new ValidationResult("WOAH! Not the right size.");
}
int totalsize = 0;
foreach (var property in _properties)
{
var propinfo = validationContext.ObjectType.GetProperty(property);
if (propinfo == null)
return new ValidationResult(string.Format("could not find {property}"));
var propvalue = propinfo.GetValue(validationContext.ObjectInstance, null) as string;
if (propvalue == null)
return new ValidationResult(string.Format("wrong property for {property}"));
totalsize += propvalue.Length;
}
if (totalsize != _expectedsize)
return new ValidationResult(ErrorMessage);
return ValidationResult.Success;
}
}
クラス:
public class Pharmacy
{
[MinimumPhoneDigits(10, Area)]
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
}
}
private string _phoneNumber;
public string Area
{
get
{
try
{
return _phoneNumber.Split(new char[] { '(', ')', '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
}
catch
{
return "";
}
}
}
}
のように、文字列を渡すつもりかもしれないと思う
Area
のように実行時にのみ知られている値を渡すことはできませんか? –'Pharmacy.Area'がどこに届いているかを示す必要がありますが、一般的に' catch {return ""; } 'は解決策集合ではなく問題集合のメンバーです。 –
あなたのコードはスローされた例外をすべて飲み込んでいます。 – Tim