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.
@Html.TextBoxFor (m => m.PositiveNumber, new { @type = "number", @class = "span4", @min = "0" }) in MVC 5 with Razor you can add any html input attribute in the anonymous object as per above example to allow only positive numbers into the input field. Pretty neat solution for front end Validation. Thanks to save my time @realaValoro :-)
How to Allow Only Positive Numbers in the Input Number Type Solutions with HTML attributes ¶ As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.
And we set the value prop to the value state. To accept only positive unsigned integer values in TextField with React Material-UI, we can check the value that’s entered into the TextField, then we can change values that aren’t accepted to a valid value.
beyond the scope of the question but you could do this same approach for any html5 input type You can also input "-" and "+" that are characters not number. This is at least partially supported in all major browsers except Opera Mini. Besides "-" and "+" characters you can input "e" character.
This accepts only positive numbers.
System.ComponentModel.DataAnnotations
[Range(1, int.MaxValue, ErrorMessage = "Only positive number allowed")]
This should be correct.
[Range(0, int.MaxValue, ErrorMessage = "Only positive number allowed.")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With