Here's my custom validator:
public class CustomRuleFileTypeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
var pdfProperty = validationContext.ObjectType.GetProperty("Pdf");
var stepProperty = validationContext.ObjectType.GetProperty("Step");
var dwgProperty = validationContext.ObjectType.GetProperty("Dwg");
bool isPdfSelected = pdfProperty != null && (bool?) pdfProperty.GetValue(validationContext.ObjectInstance) == true;
bool isStepSelected = stepProperty != null &&
(bool?) stepProperty.GetValue(validationContext.ObjectInstance) == true;
bool isDwgSelected =
dwgProperty != null && (bool?) dwgProperty.GetValue(validationContext.ObjectInstance) == true;
if (!isPdfSelected && !isStepSelected && !isDwgSelected)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
And here's the Ticket class:
public partial class Ticket
{
[Required(ErrorMessage = "Dieses Feld ist erforderlich!")]
public string? Kunde { get; set; }
[CustomRuleFileType(ErrorMessage = "Bitte wählen Sie mindestens 1 Dateiformat aus")]
public bool? Pdf { get; set; }
[CustomRuleFileType(ErrorMessage = "Bitte wählen Sie mindestens 1 Dateiformat aus")]
public bool? Step { get; set; }
[CustomRuleFileType(ErrorMessage = "Bitte wählen Sie mindestens 1 Dateiformat aus")]
public bool? Dwg { get; set; }
}
And here's part of my EditForm:
<EditForm Model="@Ticket" OnValidSubmit="@SendTicket" id="homeForm">
<DataAnnotationsValidator/>
<div class="sectionGeneral">
<div>
<label for="inputKunde">Kunde*</label><br/>
<input type="text" id="inputKunde" @bind-value="Ticket.Kunde">
<ValidationMessage For="@(() => Ticket.Kunde)"/>
</div>
<div>
<label>Format*</label><br/>
<label class="labelItem">
<input type="checkbox" @bind="Ticket.Pdf" class="checkbox"/>
<ValidationMessage For="@(() => Ticket.Pdf)" />
<div class="option_inner">
<div class="name">PDF</div>
</div>
</label>
<label class="labelItem">
<input type="checkbox" @bind="Ticket.Step" class="checkbox"/>
<ValidationMessage For="@(() => Ticket.Step)" />
<div class="option_inner">
<div class="name">Step</div>
</div>
</label>
<label class="labelItem">
<input type="checkbox" @bind="Ticket.Dwg" class="checkbox"/>
<ValidationMessage For="@(() => Ticket.Dwg)" />
<div class="option_inner">
<div class="name">DWG</div>
</div>
</label>
</div>
</div>
</div>
The ErrorMessage for e.g. Ticket.pdf (or the other types) isn't displayed, but the custom validation works. It get's displayed in the ValidationSummary though. The ValidationMessage for "Kunde" is displayed (not custom).