Reputation: 1477
I'm making an input that accepts only numbers, dots and commas; but for some reason, I can't make the input accept the commas and periods.
Code that currently does not work:
$('.numberType').keypress(function(key) {
if (key.charCode == 188 || key.charCode == 190) return true;
if (key.charCode < 48 || key.charCode > 57) return false;
})
Upvotes: 2
Views: 2039
Reputation: 1114
Whilst I accept it isn't necessarily what you want, due to potential browser requirements, styling, or specific restriction, here is a HTML5 solution using no JS:
<input pattern="^[0-9,\.]*$" />
This uses a regular expression (RegEx) to specify what's allowed, and should run native without JS.
Note, whilst the HTML5 spec suggests the pattern is always anchored to both the start and the end without the need for the ^
and $
, both Chrome and Firefox only anchor at the start without the ^
. Both will work as anchors in the RegEx, so I've included both.
Upvotes: 0
Reputation: 48600
Use the pattern
attribute on your input to handle validation when it comes time to submit your form.
<form name="input-pattern-form-example">
<label>Number:</label>
<input type="text" name="number-value" title="Number value"
pattern="^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$" />
<input type="submit">
</form>
You can use some of the patterns here for your validation.
Regular expression to match numbers with or without commas and decimals in text
Here is the pattern used in the above example:
#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$
Upvotes: 1
Reputation: 3541
This is generally not a good idea, especially from a UX point of view.
For example, how do you delete characters? You have to allow the backspace and del keys. What about the arrow keys? What about negative numbers? And if you allow the minus sign, what if a user types something like '327-762' ?
I'd say drop this and do a validation on submit, or maybe on blur
event. But do not force the focus back on the input if something is not validated, the server has to also do the validation, you can't trust user input anyway.
If you really, really want to go down this path then just as @Adjit said, you need to use the codes 44
and 46
.
Upvotes: 3
Reputation: 10305
You are using the wrong character codes for commas and periods. You can test this by adding a console.log
statement and seeing what char codes belong to which keys
$('.numberType').keypress(function(key) {
console.log(key.charCode);
if(key.charCode == 44 || key.charCode == 46) return true;
if(key.charCode < 48 || key.charCode > 57) return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="numberType"/>
Upvotes: 0