Reputation: 375
I have an html form that includes, among other things, two number fields that need to take numbers within a certain range. I'm trying to use the min and max attributes to accomplish this as such
<input type="number" id="AutoApprovalDelayInSeconds" min="0" max="2592000" step="1" placeholder="Range: 0 to 2592000"/>
<input type="number" id="AssignmentDurationInSeconds" min="30" max="31536000" step="1" placeholder="Range: 30 to 31536000" required/>
but when I enter the form with invalid input it submits with no error display or warning. I know that the number attribute is only a string representation of a number and not an integer or other numeric data type, so do I have to somehow convert this input with javascript, or am I doing something else incorrectly? Thanks!
EDIT. I originally tried opening this in Firefox, which I now know doesn't support this feature.
Upvotes: 1
Views: 3242
Reputation: 4271
assuming the form name is form
this is a barebone script. you should consider changing the input type to text so you won't have to worry about cross browser compatibility
<form id="form">
<input type="text" id="AutoApprovalDelayInSeconds" step="1" placeholder="Range: 0 to 2592000">
<input type="text" id="AssignmentDurationInSeconds" step="1" placeholder="Range: 30 to 31536000" required>
</form>
JS
var delay, duration, form;
delay = document.getElementById('AutoApprovalDelayInSeconds');
duration = document.getElementById('AssignmentDurationInSeconds');
form = document.getElementById('form');
form.onsubmit = function (e) {
e.preventDefault();
delay = parseFloat(delay.value);
duration = parseFloat(duration.value);
if(delay < 0 || delay > 2592000 || isNaN(delay)) {
delay.focus();
alert('AutoApprovalDelayInSeconds is invalid');
return;
}
if(duration < 30 || duration > 31536000 || isNaN(duration)) {
duration.focus();
alert('AssignmentDurationInSeconds is invalid');
return;
}
// all input appears to be valid so send it
form.submit();
};
Upvotes: 2
Reputation: 9347
Please bear in mind that the HTML5 input[type='number']
is not supported by many browsers, really just Chrome and IE10 (note: not Firefox).
Using Chrome I was restricted from posting the form, but on many other browsers you won't be. If you really need to restrict user input by number, and want to do some validation, then I suggest you look to JavaScript (perhaps jQuery Validate).
Upvotes: 3