I have a form that it is possible that some of the form elements (MudBlazor components), May be disabled.
The problem is that when the field is disabled I want no validation takes place because I send null instead of that field value.
But when the textfield is enabled (it is up to user to enable or disable the field using a checkbox) I want the validation occure.
But when the checkbox is unticked and the field is disabled, validation still works. I want when the field is disabled no validation occures. How to do this?
I use both fluent validation (for stringlength) and isrequired=true property at the same time on each field.
Add a boolean property to your Formmodel for the disabled input.
public class OrderModel
{
public string Name { get; set; }
public bool IsNameDisabled {get; set;}
}
And use it to disable/enable the input
<MudTextField
@bind-Value="model.Name"
Disabled="model.IsNameDisabled"
For="@(() => model.Name)"
Immediate="true"
Label="Name"
/>
Then you can include this property in fluent validation, so that Name only gets validated if the input is not disabled.
RuleFor(x => x.Name).Must(x => !string.IsNullOrEmpty(x)).When(x => !x.IsNameDisabled)
Or if you want to set it inline you could
<MudTextField
@bind-Value="model.Name"
Disabled="model.IsNameDisabled"
Required="!model.IsNameDisabled"
For="@(() => model.Name)"
Immediate="true"
Label="Name"
/>
maybe just set the value of isrequired to be
isenabled
(the field in your code), and the validation to beisenabled ? xxxx : null
?