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

3

23

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?

Bushmaster answered 23/8, 2010 at 14:5 Comment(1)
Much easier to use a regex here: #5662069Absolutely
R
27

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;
    }
}
Ramon answered 23/8, 2010 at 14:12 Comment(2)
sorry. for the trouble I should have known that. Just had a brain fartBushmaster
Why not use decimal.TryParse or something? In that way, you can support more number types than just integersBocanegra
O
74

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; }
Olander answered 13/9, 2011 at 11:6 Comment(3)
For Range, system has a ErrorMessage "The field XXX must be between XXX and XXX." So the ErrorMessage is optionalAmphetamine
Yes, you are correct. But the custom ErrorMessage is a lot more user friendly than: "The field Square Feet must be between 0 and 2147483647". ;)Olander
At least in MVC2 this does not work if the data passed in is not a valid integer. The framework will pass in the default value which is 0 and the validation will succeed, but later fail when the framework goes to actually instantiate the model and sees it cannot convert the data into an integer. It puts up the default error message at that point.Irv
R
27

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;
    }
}
Ramon answered 23/8, 2010 at 14:12 Comment(2)
sorry. for the trouble I should have known that. Just had a brain fartBushmaster
Why not use decimal.TryParse or something? In that way, you can support more number types than just integersBocanegra
C
10

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; }
Clique answered 11/1, 2016 at 4:26 Comment(1)
Zero - is not a positive integer.Connective

© 2022 - 2024 — McMap. All rights reserved.