Regex replace from number type input - javascript

I have a number type input that I want to prevent people from entering anything but numbers.
The examples I found work well with input type text fields but don't work well with number fields.
Works well :)
<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
Doesn't works well :(
<input type="number" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
Try it for yourself on JSFiddle
Please help...

I've just done some simple testing using JSFiddle and it would appear that if there is an invalid input on an <input type="number" /> element then the this.value property is returned blank.
The following line showed this result when using Chrome:
<input type="number" oninput="alert(this.value)">
JSFiddle Demo
In fact here's the reason why this happens:
The value attribute, if specified and not empty, must have a value
that is a valid floating-point number.
The value sanitization algorithm is as follows: If the value of the
element is not a valid floating-point number, then set it to the empty
string instead.
^ From the HTML5 Draft Paper section on the implementation of the number input type
This problem has taken my interest now and I've come up with a little workaround.
<input type="number" oninput="updateNum(this)">
function updateNum(e)
{
e.select();
e.value = getSelection().toString().replace(/[^\d]/g,'');
}
This has the potential to be buggy if the selection where to change between commands.
JSFiddle for the workaround

See this DEMO if you want to accept numbers with fractional part (3.14 for example)
Number: <input type="number" oninput="updateNum(this)" />
function updateNum(e) {
if (isNaN(e.value)) {
e.value = e.value.replace(/[^\d]/g,'');
}

Related

Invalid number input in HTML

I want the following Angular code (using Angular 12) to show "Illegal award number" when the input is invalid.
As you can see in the screenshot, when the number is -1 (smaller than the min value defined on the input), the div is shown as expected.
However, if I input some text such as 1-, or an expression 3-4 and hover my mouse over it, the browser will tell me my input is not a valid number, but the div is not shown (which means awardInputRef.invalid is false).
Why is that?
Here is the relevant code
<label class="form-label" for="awardInput">Award</label>
<input class="form-control" id="awardInput" type="number" min="0" max="10" step="0.1" [(ngModel)]="award"
#awardInputRef="ngModel" />
<div *ngIf="awardInputRef.invalid">Illegal award number</div>
PS:
If I add (blur)="onAwardBlur($event)" to the award input and add a function in my component
onAwardBlur(event) {
console.log(event);
}
then debug the code by logevent.target.validity.valid, I will see it is false.
The code is available on stackblitz. The Angular version there is 11, and the div does not show up even if I input -1 there.
As part of Angular version 12 only min and max directive are implemented that's why stackblitz version is not working.
You can workaround your issue using native Input element ValidityState
Define another one template variable on input element
<input class="form-control" id="awardInput" type="number" min="0" max="10" step="0.1" [(ngModel)]="award"
#awardInputRef="ngModel" #inputRef />
Then you can add some custom validity something like this:
<div *ngIf="awardInputRef.invalid
|| inputRef.validity.badInput && (awardInputRef.dirty || awardInputRef.touched)
">Illegal award number</div>
Working Example
input: -1
Your Using [ - ] this special character so the filed goes awardInputRef.invalid.
so div shown.
input: 1-
Your using number first it goes awardInputRef.valid or something else but not awardInputRef.invalid .
so the div not shown in this case.
you just inspect the field and find the before after changes .

Only accept quarterly floats

I would like an HTML input validated on integer # (hourly), #.5 (half hourly) and #.25 (quarter).
I tried using HTML input type='number', but this seems to be fixed integers only. Does anybody have any clue on how to make a system that restricts on quarters?
Guessing you haven't tried step attribute yet?
Also believe you want it to be a time input since you mention hourly
:invalid{
color: red
}
<input type="time" step="900"><br>
<input type="number" step="0.25">

How to set maximum number of characters in number type textbox?

I have one textbox which is of number type. I want it to accept maximum of 16 digits, not more than that. For that I have tried with "maxlength" attribue and "max" attribute both. But its not working. Can anyone provide me solution?
<input type="number" id="dummy" max="16" />
Edit: I need to enter only whole number since it is used for account number of bank.
There are a few of these "how do I further control type="number" fields" questions here on SO. It boils down to:
You make it a type="number" and accept that you can't further mask the input vs. what the browser does to implement a numeric input, or
You make it type="text" and use pattern and/or maxlength to enforce the specific pattern you want, and accept that the browser won't add a specific UI for numbers.
Input type number doesn't support "maxlength" attribute. You can specify "max" attribute (HTML5), which is the highest number user can input. Something like this: <input type="number" max="999999999999" id="dummy" step="1" min="0">.
Edit: Also specify step attribute to 1.

Event return null value when user enter decimal on input type number

Edit working on Firefox, only Chrome bug (and maybe others)
I try to get all event from a simple <input type="number" step="any" /> :
$('input[type=number]').on('input', function() {
$('#value').text($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="any"/>
<br/>
<strong>Value:</strong> <span id="value"></span>
All append good when I press, or update the number. But when I try to put a decimal point . the value is null.
I use jQuery here, but the problem is the same with Vanilla JS.
The closest I can get is:
$('input[type=number]').on('input', function() {
$(this).select();
var value = window.getSelection().toString();
window.getSelection().empty();
$('#value').text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="any"/>
<br/>
<strong>Value:</strong> <span id="value"></span>
Notice that when you type something, the field loses its focus...
i think it is issue with type of input field, decimal point (the dot) is not a number but it is necessary for numbers, so i guess it is the glitch in the matrix.
here is a fiddle where type is text and it is working fine.

HTML Field Type Input Number Only or Letter Only Without JavaScript

I create a form, where one field should only be filled with numbers.
I want that field can be filled only with numbers since entering input.
Like this example :
How Can I Use Javascript to Allow Only Numbers to Be Entered in a TextBox?
I've tried using Regex, but when I try to input is still able to enter letters.
<input type="number" min="2" pattern="^[0-9]" class="andi_input required-entry" name="amount" id="amount" required title='Only Number' />
I want it when input to field and not after click the Submit button and the message appear and inform that the field can only be filled with numbers.
I also try to add validate-number, but the result is the same.
How, without javascript, so that the field can only be filled with numbers or letters?
Whether for this kind of case have to use JavaScript or is there another way without JavaScript?
HTML 5 uses the type="number" so make sure that the browser that you are using is compatible. Check it out in action here.
You should check browser compatibility.
You're right with <input type="number" pattern="^[0-9]" />.
Your regex rule is :
^[0-9] :
^ assert position at start of the string
[0-9] match a single character present in the list below
(0-9 a single character in the range between 0 and 9)
You can check your regex here.
I use to use HTML5 Validation and jQuery one because IE is capricious most of the time.
UPDATE :
Without Javascript it's not possible to check pattern on real time. I suggest you to use a jQuery library like : http://www.jqueryscript.net/form/jQuery-Plugin-For-Formatting-User-Input-with-Specified-Pattern-formatter-js.html.
Here is a OneLiner:
<input type="number" onkeypress="return /[0-9]/i.test(event.key)">
or
<input type="text" onkeypress="return /[a-z]/i.test(event.key)">

Categories

Resources