Question

I have a view model ApplicantProfileModel that works in all respects. It declares a property

[HiddenInput(DisplayValue = false)]
public int Id { get; set; }

and this property is present in a partial view like this

@model Comair.RI.UI.Models.ApplicantProfileModel
@Html.ValidationSummary(true)
<fieldset>
    <legend></legend>
    <ul class="form-column">
        @Html.HiddenFor(m => m.Id)
    .....

I have the following Fluent Validation rule for this property:

RuleFor(p => p.Id).NotEmpty().WithMessage("Id is empty. Messsage may have been tampered with.");

An int with a value of zero is certainly not 'empty'. I know I can change the rule to not equal to zero, but that doesn't solve my problem and answer my question as to why an int of value 0 is considered empty by fluent validation?

Was it helpful?

Solution

Because an int is a value type and can't not have a value. Under the hood FluentValidation checks against default for that type, which I believe would be 0 for int. If you can make your Id a nullable int you can get that behaviour. Otherwise I would do as you suggest and check for not equal to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top