In my previous post New TextMode proprty values for TextBox in ASP.Net, I talked about some new values introduced for input HTML element's type in ASP.Net 4.5 server control In this post I will discuss how to take advantage of these new attribute values to allow your browser to validate and control user's input without you having to write extra client side code.
To see these attributes in action below, you will need to use Chrome browser.
<input type="number" min="1.5" max="50.5" step="1.25" />
In this post I will focus behavior of text box when type attribute value is set to number. As the value of this attribute suggests, by setting this value you indicate to the browser that this text box will only accept numeric type data. This means that you can only enter any valid floating numbers in the text box. If you will enter text that does not represent a numeric value, the browser will erase that input from text box. For example if you enter x.y in the text box, the moment the text box looses focus, the text will be gone. There are more attributes that compliment type value set to number.
By setting attribute min to a valid numeric number you indicate the minumum value the text box will accept. Currently Chrome does allow to enter value that is out of MIN range. It will bring it back to MIN value when you try to use numeric updown control to manipulate it,
By setting attribute max to a valid numeric number you indicate the maximum value the text box will accept. Currently Chrome does allow to enter value that is out of MAX range. It will bring it back to MAX value when you try to use numeric updown control to manipulate it,
This attribute defines the step increment for updown control. If you do not set the value for this attribute, then default value is 1. And it also turns the control into accepting only integer values if min attribute is not set to a floating point number. So it is important to set min attribute if you want to deal with floating point numbers. The value of step attribute should be a valid floating point number.
The discussion will not be complete without going over some of the pros and cons of using these new attributes.
One thing that lack with using browser's attributes is that there is not way to let user know that he or she is violating some constraint. With ASP.Net validators or some custom implementation you are able to show informative error message. But I did not find browser triggering any event or displaying some default message if input does not satisfy some constraint set by attributes.
Despite some limitations, I think it will be worth setting up appropriate attribute values to let browser do its magic and then add your own light weight validator on top of it.