Skip to content

Refactor repeated GUID validation into a reusable FluentValidation extension #536

@ziagham

Description

@ziagham

Summary

Currently, multiple validator classes have identical BeAValidGuid methods to validate GUIDs. This results in repeated code and violates the DRY principle.

We should refactor this by creating a reusable FluentValidation extension method to encapsulate GUID validation logic and optionally support localized error messages.

Proposed Solution:

  • Create a new static class ValidatorExtensions, under Extensions folder in the FlowSynx.Application project to hold extension methods for IRuleBuilder.
  • Add a method MustBeValidGuid that validates a string is a valid GUID.
  • Update existing validators to use the new extension method instead of repeating BeAValidGuid.
  • Ensure localization support can be injected for error messages.
public static class ValidatorExtensions
{
    public static IRuleBuilderOptions<T, string> MustBeValidGuid<T>(
        this IRuleBuilder<T, string> ruleBuilder, string message)
    {
        return ruleBuilder
            .Must(id => Guid.TryParse(id, out _))
            .WithMessage(message);
    }
}

Usage in validator:

For example in the WorkflowDetailsValidator.cs, it will change to this:

public class WorkflowDetailsValidator : AbstractValidator<WorkflowDetailsRequest>
{
    public WorkflowDetailsValidator(ILocalization localization)
    {
        RuleFor(x => x.WorkflowId)
            .NotNull()
            .NotEmpty()
            .WithMessage(localization.Get("Features_Validation_WorkflowId_MustHaveValue"));

        RuleFor(x => x.WorkflowId)
            .MustBeValidGuid(localization.Get("Features_Validation_WorkflowId_InvalidGuidFormat"));
    }
}

Tasks:

  • Implement MustBeValidGuid extension method
  • Refactor all existing validators to use this extension method
  • Add unit tests for the extension method

Metadata

Metadata

Assignees

No one assigned

    Labels

    C#C# related codeenhancementNew feature or requesthelp wantedExtra attention is neededrefactoringRefactoring code

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions