qinking126
qinking126

Reputation: 11885

asp.net mvc3, why dataannotation validates without Validator Attributes?

I have a simple ViewModel

public class ProductViewModel
{
    [Required(ErrorMessage = "This title field is required")]
    public string Title { get; set; }
    public double Price { get; set; }
}

here's my form based on this View Model.

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>ProductViewModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Title)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Title)
        @Html.ValidationMessageFor(model => model.Title)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Price)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Price)
        @Html.ValidationMessageFor(model => model.Price)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

I dont want to validate the price field. but it got automatically validated, if nothing entered, will show this field is required. I notice I use double for price. If I changed it to "string". validation is removed. why type "double" cause automatic validation?

Upvotes: 0

Views: 250

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

Because double is a value type, and cannot be null. You could have made it double? or Nullable<double> and it would be fine.

Upvotes: 1

vcsjones
vcsjones

Reputation: 141638

I dont want to validate the price field. but it got automatically validated, if nothing entered, will show this field is required

Because a double is a value type, which cannot be null. If you want the value to allow not having a value, use a nullable double: double? on your model:

public class ProductViewModel
{
    [Required(ErrorMessage = "This title field is required")]
    public string Title { get; set; }
    public double? Price { get; set; }
}

Upvotes: 1

Related Questions