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

[Proposal]: Add custom validation to constructor/Parse/TryParse #156

Open
pergardebrink opened this issue Jan 8, 2025 · 1 comment
Open

Comments

@pergardebrink
Copy link

pergardebrink commented Jan 8, 2025

In some scenarios, it might be good to validate the input value even if the underlying type supports the actual value. For example, I might want to use an int, but don't want to support negative numbers or 0, or maybe the value has to be greater than 1000.
Or I want to use a string as underlying type, but want to have some constraints on which characters can be used, etc.

If I could declare a partial method or similar that would be called whenever the parsed value is about to be stored in Value and return false for TryParse and throw on constructor or Parse. That could solve this, but not sure if there are other options available already?

Example idea with int:

[StronglyTypedId(Template.Int)]
public partial struct MyIntId
{
    private partial bool IsValid(int value)
    {
        return value > 1000;
    }
}

Example idea with string (only allowing A-Z and 0-9):

[StronglyTypedId(Template.String)]
public partial struct MyStringId
{
    [GeneratedRegex("^[a-zA-Z0-9]*$")]
    private static partial Regex validationPattern();

    private partial bool IsValid(string value)
    {
        return validationPattern().IsMatch(value);
    }
}
@pergardebrink pergardebrink changed the title Proposal: Add custom validation to constructor/Parse/TryParse [Proposal]: Add custom validation to constructor/Parse/TryParse Jan 8, 2025
@andrewlock
Copy link
Owner

The short answer is that you could implement this feature now in your apps with the custom template support 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants