Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to know if a field is required #175

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/ExpressiveAnnotations/Attributes/RequiredIfAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,39 @@ protected override ValidationResult IsValidInternal(object value, ValidationCont
{
AssertNonValueType(value);

var isEmpty = value is string && string.IsNullOrWhiteSpace((string) value);
var isEmpty = value is string && string.IsNullOrWhiteSpace((string)value);
if (value == null || (isEmpty && !AllowEmptyStrings))
{
Compile(validationContext.ObjectType);
if (CachedValidationFuncs[validationContext.ObjectType](validationContext.ObjectInstance)) // check if the requirement condition is satisfied
return new ValidationResult( // requirement confirmed => notify
FormatErrorMessage(validationContext.DisplayName, Expression, validationContext.ObjectInstance),
new[] {validationContext.MemberName});
new[] { validationContext.MemberName });
}

return ValidationResult.Success;
}

/// <summary>
/// Indicates if the property is required with respect to the attribute and model value
/// </summary>
/// <param name="value">Model value to test</param>
/// <returns>
/// True if the property is required, false otherwise
/// </returns>
public bool IsRequired(object value)
{
if (value == null)
return false;

Type type = value.GetType();
if (!CachedValidationFuncs.ContainsKey(type))
{
CachedValidationFuncs[type] = Parser.Parse<bool>(type, Expression);
}
return CachedValidationFuncs[type](value);
}

private void AssertNonValueType(object value)
{
if (PropertyType == null)
Expand Down