How to do Integer model validation in asp.net mvc 2

假装没事ソ 提交于 2019-11-30 13:10:24

问题


I have a registration form and the user must enter the square footage of their house. I would like this value to be only an integer. Is there a way to validate this value using attributes asp.net mvc?


回答1:


yes, it is, but you will have to make a flat version of the object you are wanting to create, because the validation with attributes only runs AFTER MVC has converted your data into the model. which, when your value is an int, will fail to validate if the user did not enter an int, and you will get a MVC error message in stead of your errormessage.

can you post the object you are wanting to make?

with a flat version i mean all datetimes and ints are stings in the flat version.

then i use this:

    [DisplayName("Square meters")]
    [PosNumberNoZero(ErrorMessage = "need a positive number, bigger than 0")]
    public string squaremeters { get; set; }

in the same file

public class PosNumberNoZeroAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null) {
            return true;
        }
        int getal;
        if (int.TryParse(value.ToString(), out getal)) {

            if (getal == 0)
                return false;

            if (getal > 0)
                return true;
        }
        return false;

    }
}

if my modelstate is valid then, i use AutoMapper to convert my FlatModel into my Model, which is just 2 lines of code.

edit: if 0 is a valid number:

public class PosNumberAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null) {
            return true;
        }
        int getal;
        if (int.TryParse(value.ToString(), out getal)) {

            if (getal >= 0)
                return true;
        }
        return false;
    }
}



回答2:


Realise this has already been answered, but Stefanvds' answer is uneccessarily complicated. Just use MVCs built in validation attributes:

[DisplayName("Square Feet")]
[Required(ErrorMessage = "Square Feet is Required")]
[Range(0, int.MaxValue, ErrorMessage = "Square Feet must be a positive number")]
public int SquareFeet { get; set; }



回答3:


I usually use the range attribute like this:

Positive int:

[Range(0,int.MaxValue)]
public int Id { get; set; }

Negative int:

[Range(int.MinValue,-1)]
public int Id { get; set; }

Any int:

[Range(int.MinValue,int.MaxValue)]
public int Id { get; set; }



回答4:


Well using Range for an int field will not work if you have some letters like "a".
The error Handler is not called (ASP.NET CORE 1.0 RC2).



来源:https://stackoverflow.com/questions/3548300/how-to-do-integer-model-validation-in-asp-net-mvc-2

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