How To Create A Dollar Amount Input Field In An Html Form?
Solution 1:
I think you are going to have to validate it. This post has some good regex for validation dollar amounts: Currency validation. It also has some good points for how to trim so that a user can't enter $412.234 or anything like that.
Solution 2:
You cannot create, in HTML, a text box that has a particular character fixed in it. There is hardly any need either, since it is more natural for a user to type 12.34 (when specifying a sum of money) than to type 1234 and have a period inserted automatically.
You can specify the required format using the HTML5 pattern
attribute. It is not supported by all browsers yet, but it does no harm when not supported, and it performs the checks even when JavaScript is disabled. You should add JavaScript checking of course, and in a simple case like this, it might be better to write the code directly instead of using any library:
<inputpattern="\d?\d\.\d\d"maxlength=5size=5onchange="check(this)"><script>functioncheck(elem) {
if(!elem.value.match(/^\d?\d\.\d\d$/)) {
alert('Error in data – use the format dd.dd (d = digit)');
}
}
</script>
The regular expression used accepts both dd.dd and d.dd (omit the ?
to allow the first format only).
The example uses alert
for simplicity; in a real page, you should use some less disruptive way of signaling the error to the user (typically, writing text to an area reserved for such messages), but the best way to do that depends on the design of the page as a whole.
(It might seem more logical to use <input type=number min=0 max=99.99 step=0.01 ...>
, but this would raise serious localization issues, and browsers implement type=number
rather poorly if at all. Most importantly, there is no guarantee that the data sent would conform to the format required. E.g., in Chrome, using the controls created by the browser, the number would be stepped from 0.09 to 0.1 and not 0.10, from 0.99 to 1 and not 1.00 etc.)
Post a Comment for "How To Create A Dollar Amount Input Field In An Html Form?"