Warn about empty properties with one line of code


If you are like me and have an inner purpose to enhance the life of the editors using your applications, this one is for you.

Estimated read time : 2 minutes

Jump to

Key takeaways

  • Make editors life easy as one, two, three
  • Property validation

Make life easy for others and the result will be great  

I have previously talked about the importance of validating and giving the editor error messages after the instance of content is created.

Here is an example of how to warn the editor about fields that are missing values. For properties that are important but not critical.

This is an easy way to make a big difference with one line of code. To warn them and remind them that they missed a field (maybe the SEO fields editors tend to forget?).

Validator, attribute and properties

Here is the actual validator. We go through all the properties with the attribute set and check them for null value. Here you can modify the validator to your needs.

public class ContentValidatorForAttribute : IValidate<ContentData>
{
    public IEnumerable<ValidationError> Validate(ContentData instance)
    {
        IEnumerable<PropertyInfo>? properties = instance
            .GetType()
            .BaseType?
            .GetProperties()
            .Where(x => x.GetCustomAttributes(typeof(WarnIfNullAttribute), false)
                .Any());

        //return no warnings if there is no properties with WarnIfNullAttribute
        if (properties == null || !properties.Any())
        {
            return Enumerable.Empty<ValidationError>();
        }
        
        var warnings = new List<ValidationError>();

        foreach (var item in properties)
        {
            if (instance[item.Name] == null)
            {
                var attributeSettings = item.GetCustomAttribute(typeof(WarnIfNullAttribute));
                var text = ((WarnIfNullAttribute)attributeSettings).WarningText;
                warnings.Add(new ValidationError()
                {
                    ErrorMessage = text,
                    PropertyName = item.Name,
                    ValidationType = ValidationErrorType.PropertyValidation,
                    Severity = ValidationErrorSeverity.Warning
                });
            }
        }
        return warnings;
    }
}

Here is the attribute with the error message.

public class WarnIfNullAttribute : Attribute
{
    public string WarningText { get; set; }

    public WarnIfNullAttribute(string text)
    {
        WarningText = text;
    }
}

And the result will be one line of code that warns the editor of the field is null. No need for larger validators for this.

[Display(Name = "Some property of any kind", Order = 100)]
[WarnIfNull("Warning this property is empty")]
public virtual string? SomeString { get; set; }