MVC4 FoolProof Data Annotations - How to check that field does not equal to zero?

佐手、 提交于 2021-02-04 21:32:22

问题


I am trying to use MVC Foolproof library to validate my model and show error message respectively. However when I use Foolproof validation, on clicking the submit button even the regular validation is not showing.

My requirement is that I have a numeric textbox and it should not be null or zero.The textbox value is calculated based on the value selected from the previous dropdownlist.

Below is the code for both fields in the model with data annotation,

using Foolproof;

  [Required(ErrorMessage = "Fee is not given", AllowEmptyStrings = false)]
    [NotEqualTo("0",ErrorMessage="Duration cannot be zero")]
    public Nullable<int> Duration { get; set; }

Html Textbox

 @Html.TextBoxFor(m => m.MultiCourse.Duration,
        new { @class = "form-control", @placeholder = "Course Duration", @id = "txtCourseDuration" })
            @Html.ValidationMessageFor(m => m.MultiCourse.Duration)

Bundle Config class

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/plugins/jQueryVal/jquery.unobtrusive*",
                    "~/plugins/jQueryVal/jquery.validate*",
                    "~/plugins/jQueryVal/mvcfoolproof.unobtrusive*"));

回答1:


The foolproof [NotEqualTo] attribute compares the value of the property with the value of another property. In your case this would throw an exception because you model does not (and cant) contain a property named 0.

If only positive values are allowed, then you could use a [Range] attribute

[Range(1, int.MaxValue, ErrorMessage = "Duration must be greater than zero")]
public Nullable<int> Duration { get; set; }

Alternatively if negative values were allowed, you could include a property in your view model (say) int InvalidDuration and use

[NotEqualTo("InvalidDuration", ErrorMessage="Duration cannot be zero")]
public Nullable<int> Duration { get; set; }

and include a hidden input in the view

@Html.HiddenFor(m => m.InvalidDuration)


来源:https://stackoverflow.com/questions/33095170/mvc4-foolproof-data-annotations-how-to-check-that-field-does-not-equal-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!