DataType has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint attribute.
Adding a new core DataType is not possible since the DataType enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute. Then you can add a new constructor with your own DataType enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType)
{ }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();
You can also go through this link. But I will recommend you using Jquery for the same.
Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).
If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.
i was just playing around with HTML5 input type=number. while its not supported by all browsers I expect it is the way going forward to handle type specific handling (number for ex). pretty simple to do with razor (ex is VB)
@Html.TextBoxFor(Function(model) model.Port, New With {.type = "number"})
and thanks to Lee Richardson, the c# way
@Html.TextBoxFor(i => i.Port, new { @type = "number" })
beyond the scope of the question but you could do this same approach for any html5 input type
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.
Please use the DataType attribute. This will accept negative values so the regular expression below will avoid this:
[DataType(DataType.PhoneNumber,ErrorMessage="Not a number")]
[Display(Name = "Oxygen")]
[RegularExpression( @"^\d+$")]
[Required(ErrorMessage="{0} is required")]
[Range(0,30,ErrorMessage="Please use values between 0 to 30")]
public int Oxygen { get; set; }