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

Docs: Example for IValidatableObject #5707

Open
stsrki opened this issue Aug 21, 2024 · 0 comments
Open

Docs: Example for IValidatableObject #5707

stsrki opened this issue Aug 21, 2024 · 0 comments
Assignees
Labels
Area: Documentation Something is missing in the documentation.
Milestone

Comments

@stsrki
Copy link
Collaborator

stsrki commented Aug 21, 2024

          The IValidateObject is indeed a good option. I did not realize that the validations could be implemented in a flexible way. Below an example , Text1 is now fixed and Text2 is dependent on the Status.

I already realized that custom validators is possible as well, but then I have to rewrite the validators which I find not a great solution.
Thanks for the solution.

@using System.ComponentModel.DataAnnotations;

<Select @bind-SelectedValue=mydata.Status>
    <SelectItem>New</SelectItem>
    <SelectItem>Completed</SelectItem>
</Select>


<Validations @ref=valref1 Model=mydata Mode="ValidationMode.Manual">
    <Validation>
        <TextEdit @bind-Text=mydata.Text1></TextEdit>
    </Validation>

    <Validation>
        <TextEdit @bind-Text=mydata.Text2></TextEdit>
    </Validation>
</Validations>


<Button Background="Background.Primary" @onclick=Submit>Submit</Button>

@code {
    someData mydata=new();
    Validations valref1;

    async Task Submit()
    {
        valref1.ClearAll();
        await valref1.ValidateAll();
    }

    class someData : IValidatableObject
    {
        [Required]
        public string Text1 { get; set; }

        public string Text2 { get; set; }
        public string Status { get; set; } = "New";

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Status == "Completed")
            {
                if (string.IsNullOrEmpty(Text2))
                {
                    yield return new ValidationResult("Text2 is required", new[] { nameof(Text2) });
                }
            }
        }
    }
}

Originally posted by @blenke in #5705 (comment)

@stsrki stsrki self-assigned this Aug 21, 2024
@stsrki stsrki added the Area: Documentation Something is missing in the documentation. label Aug 21, 2024
@stsrki stsrki added this to the 1.6 support milestone Aug 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: Documentation Something is missing in the documentation.
Projects
Status: 🔙 Backlog
Development

No branches or pull requests

1 participant