Replies: 1 comment 1 reply
-
Hi! It's looks like I didn't predict all possible cases. I can offer a quick solution for now, and I'll try to create a better solution in the future.
public static TNext GreaterThan<TObject, TProp, TNext>(
this IRuleBuilderInitial<TObject, TProp?, TNext> ruleBuilder,
Expression<Func<TObject, TProp?>> valueToCompareExpression,
IComparer? comparer = null,
ValidationMessageType validationMessageType = ValidationMessageType.Error)
where TNext : IRuleBuilder<TObject, TProp?, TNext>
where TObject : IValidatableObject
where TProp : struct, IComparable<TProp>
{
return ruleBuilder.SetValidator(new GreaterThanValidator<TObject, TProp?, TProp?> (valueToCompareExpression, comparer, validationMessageType));
} Behavior: valid if any of values is null. Comparison result if both are not null. public static TNext GreaterThan<TObject, TNext>(
this IRuleBuilderInitial<TObject, decimal?, TNext> ruleBuilder,
Expression<Func<TObject, string>> valueToCompareExpression,
ValidationMessageType validationMessageType = ValidationMessageType.Error)
where TNext : IRuleBuilder<TObject, decimal?, TNext>
where TObject : IValidatableObject
{
return ruleBuilder.SetValidator(new GreaterThanValidator<TObject, decimal?, string> (valueToCompareExpression, new DecimalStringComparer(), validationMessageType));
}
private class DecimalStringComparer : IComparer
{
/// <inheritdoc />
public int Compare(object x, object y)
{
var left = (decimal?)x;
var isRightDecimal = decimal.TryParse((string)y, out var right);
var comparer = Comparer<decimal?>.Default;
return isRightDecimal
? comparer.Compare(left, right)
: comparer.Compare(left, null);
}
} Behavior: valid if any of values is null. Also valid if string is not valid decimal number. Comparison result if both are not null and string is valid decimal. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I am using your library in one of my projects for user input validations but I am not sure how to handle two cases
1 - validating a ViewModel which has two
double?
properties and one of them has to be greater than the other one (for two double's I can use GreateThan which works flawlesly but I am not sure how to use it for nullables)2 - same as above but I have two strings which contain a double value and one of them should be greater than the other one. I tried to use
builder.TransformToDouble(string)
but I did not manage to compare it with the other stringIs it possible to compare such data types?
Thanks,
Libor
Beta Was this translation helpful? Give feedback.
All reactions