I have strange issue. ModelState has error. But I don`t have a rule for it. No filters, no rules in validator file.
My code. ViewModel:
[Validator(typeof(TestValidation))]
public class PayerPayRateViewModel
{
public int TestId { get; set; }
public bool AllServices { get; set; }
public int ParentEntityId { get; set; }
}
Validator
public class TestValidation : BaseEntityRepositoryValidator<Core.Domain.Model.Entities.Payer, PayerPayRateViewModel>
{
public TestValidation()
{
RuleFor(x => x.ParentEntityId).Must(CheckUniqueService);
}
protected bool CheckUniqueService(PayerPayRateViewModel model, int value)
{
if (model.AllServices)
{
return true;
}
return false;
}
}
And if I have TestId with value 0 I get “TestId: Field is required“.
When I remove validation attribute from Viewmodel class I get “A value is required.” error.
Why it happens?
Because you are attempting to bind an empty string to a non-nullable type. If you want this to happen use nullable types:
By default there’s an implicit Required attribute applied to all non-nullable types (think integers, datetimes, decimals, …).
By the way you could disable this default behavior: