Reputation: 5375
My Blazor application has two forms in different components. Both forms use he same view model. Though the model is the same, different fields are displayed in the components. E.g. the first component's form does not have the UnitPrice field, but the second does. I use a simple validation:
[Required(ErrorMessage = "Unit Price is required.")]
[Range(0.01, double.MaxValue, ErrorMessage = "Unit Price must be greater than 0")]
public double UnitPrice { get; set; }
Unfortunately, when the first form is displayed and submitted, the missing field is validated, and the validation fails. Is there any way to do it without splitting the model or using custom validation?
Upvotes: 2
Views: 2079
Reputation: 3402
Example as requested:
public interface IForm
{
int FormStatus { get; set; }
// Your other fields that are always shared on this form...
}
public class Form1 : IForm
{
public int FormStatus { get; set; }
[Required(ErrorMessage = "Unit Price is required.")]
[Range(0.01, double.MaxValue, ErrorMessage = "Unit Price must be greater than 0")]
public decimal UnitPrice { get; set; }
}
public class Form2 : IForm
{
public int FormStatus { get; set; }
[Required]
public string Name { get; set; }
// I made this up but it demonstrates the idea of encapsulating what differs.
}
Your shared Blazor Component would be something like.
// SharedFormFields.razor
<input type="text" @bind-Value="_form.FormStatus">
@code {
[Parameter] private IForm Form { get; set; }
}
And then your consuming components/pages
@page "/Form1"
<EditContext Model=_form1>
<SharedFormFields Form=_form1>
<input type="number" @bind-Value="_form1.UnitPrice">
</EditContext
@code {
private Form1 _form1 = new()
}
Upvotes: 1
Reputation: 5375
I used conditional validation by deriving my view model from IValidatableObject and implementing it:
public class MyViewModel : IValidatableObject
{
...
public double UnitPrice { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (StatusId >= (int)Models.Status.ReadyForReview) // my condition
{
if (UnitPrice == 0)
{
result.Add(new ValidationResult("Unit Price is required."));
}
else if (UnitPrice < 0)
{
result.Add(new ValidationResult("Unit Price must be greater than 0."));
}
}
return result;
}
}
Upvotes: 0