I have a custom validation attribute for validating decimal properties
public sealed class DecimalAttribute : ValidationAttribute
{
public DecimalAttribute()
{
this.ErrorMessage = "The input must be a decimal number";
}
private object Value { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
this.Value = value;
return base.IsValid(value, validationContext);
}
public override bool IsValid(object value)
{
if (this.Value == null) return false;
decimal result;
return decimal.TryParse(this.Value.ToString(), out result);
}
}
However when it doesn't work and when I bind the textbox to that property and input an invalid value into the textbox the message "Value '' could not be converted" is displayed instead of the error message of the my custom validation attribute.
Interestingly, I've figure it out that the other validation attributes like "Required" does not work on the numeric properties either.
Edit
My bind part is:
<TextBox>
<TextBox.Text>
<Binding Path="Price" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True">
<Binding.ValidationRules>
<local:DecimalValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
My Solutuion
This is the way I've solved my problem. I'm not sure if its is the best way however I share it for any recommandations of yours.
I've actually used two properties, one for binding and validating and the other for saving data in the database
[NotMapped, Decimal]
public string PriceString
{
get { return _priceString; }
set { if (SetValue(ref _priceString, value)) OnPropertyChanged("Price"); }
}
public decimal Price
{
get
{
decimal result;
decimal.TryParse(this.PriceString, out result);
return result;
}
set { PriceString = value.ToString(); }
}
Now it works exactly what I need.
Please make your comments, give your recommendations and provide any better solutions please.