Search code examples
c#asp.net-mvcasp.net-mvc-5

How to allow only positive number to be entered in editorforfield in asp.net mvc 5


I want a field to allow on positive number. I tried below attempt:

Model

[Required]
[GreaterThanZero(ErrorMessage = "Only positive number allowed.")]
public int PositiveNumber { get; set; }

View

  <div class="form-group">
            @Html.LabelFor(model => model.PositiveNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(m => m.PositiveNumber)
                @Html.ValidationMessageFor(model => model.PositiveNumber, "*", new { @class = "text-danger" })
            </div>
        </div>

Custom Validation

  public class GreaterThanZero : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var x = (int)value;
            return x > 0;
        }
    }

Question: Above solution works fine. I want to know is there any simple way to achieve it. By just using some inbuilt framework annotation/helpers or even FoolProof?

Kindly note that: using editorfor helped to allow only numbers (it is smart) but how about just the positive numbers.


Solution

  • This accepts only positive numbers.

    System.ComponentModel.DataAnnotations
     [Range(1, int.MaxValue, ErrorMessage = "Only positive number allowed")]