Integer validation against non-required attributes in MVC

后端 未结 4 1441
谎友^
谎友^ 2020-12-21 04:35

I\'ve trying to validate a property on a model I have. This property is NOT required, and so if its invalid MVC seems to be ignoring it. I\'ve even created a custom Validati

4条回答
  •  庸人自扰
    2020-12-21 05:08

    I found a workaround that I kind of like. The problem I ran into was a similar issue, where the value had to be greater than 0 and a number, so once I tried to cast the 9999999999 (invalid) string as a number it threw an exception and didn't show that the model state has an error message on the post. I hope this is on topic since it sounds like "Rules don't seem to apply correctly when I type in an invalid number"

    Since my number had to be positive I intercepted the value into an anonymous type object (dynamic) and used it as an intercepting body between the model's user and the private int property. When I did that, the Data Annotations worked as expected.

        public dynamic MyProperty
        {
            get { return _myProperty; }
            set
            {
                try
                {
    

    /I have to convert the value to String because it comes in as String[], and if there is more than one value then it should be problematic, so you join it together with an invalid character and throw an error, or you take the first value/ _myProperty = = Convert.ToInt32(String.Join("a",value)); } catch (Exception e) { _myProperty= -1; } } }

        private int _myProperty;
    

提交回复
热议问题