Restrict Exponents and periods(.) in numeric textbox html - javascript

I have a numeric textbox, by default numeric textbox allows Exponents and periods.
How do i restrict that?
One of the method i can think of is using string.replace on input event however it is not working as expected. Below is my code..
HTML
<input type='number' class='number'>
JavaScript
$(".number").on('input', function () {
this.value = this.value.replace(/e|E|\./g, ''); // Remove e, E, and period(.)
if (this.value.length > 4) {
this.value = this.value.slice(0, 4);
}
});
When i enter string '2e' in textbox, entire input is getting removed if above code is ran. i just wants to remove e, E or period from input string not entire input.
Is there a way to achieve this.
JSfiddle
Answer BY nichel is working like a charm, now my problem is how do i restrict the same in PASTE event.?

So basically you want to allow just numbers? Then restrict the keys by keycode & remove excess chars on paste
$(".number").keypress(function(e){
return e.keyCode>47&&e.keyCode<58;
}).paste(function(){
$(this).val($(this).val().replace(/\D/g,''));
})
And since you'd like the max length to be 4, just add max="9999":
<input type='number' class='number' max="9999">

input[type=number] returns ""(blank string) if input value is not valid.
You can refer this post for more information.
I would suggest you to use input[type=tel] instead. It also has a maxLength attribute so you so not have to worry about trimming extra values.
You can even replace your regex to /[^0-9]/. This will replace all characters except numbers.
Sample Fiddle.
So you final code would look like: JSFiddle

Related

Input box issue with max-length and match

I am using max length to limit my input to 6 numbers. The issue is it stops after 6. I think the issue is with the regex match I am using to separate the input and the max length.
<input type="text" ng-keyup="addHyphen($event)" id="sortcode" name="sortcode" maxlength="6" ng-model="data.branchTransitNumber" required numbers-only/>
Script:
$scope.addHyphen = function() {
// $scope.dashed= angular.element($event.target.value);
var ele = document.getElementById('sortcode');
ele = ele.value.split('-').join('');
$scope.data.branchTransitNumber = ele.match(/.{1,2}/g).join('-');
};
Expected in input: 11-11-11
Currently: 11-11-1
I am also not receving any console errors also.I think the regex wants to put - after two numbers and max length won't allow additional input.
EDIT:
After removing the max-length its is working. But how to make it work along with max-length
#Duck_dragon, maxlength attribute is used to restrict user to enter specified no. of characters. here you have set maxlength="6" thats why it will only allow six characters in input box. Note here it also consider - in calculation.
so if you want to allow input like 11-11-11 then you have to set maxlength="8"

Detecting Period Symbol as not Valid against Number Input Pattern Using JavaScript

I have an input tag of type number with pattern validation attached to it that has at least taken care of eliminating the 'e' '+' '-' characters from being input. However the '.' symbol still gets through for some reason. Here are the relevant portions of code from my program:
<input type="number" id="job-priority" min="1" max="99" pattern="[0-9]+" placeholder="1 (High) — 99 (Low)" style="width:186px; padding-left:14px; text-align:center;">
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
});
document.getElementById('job-priority').addEventListener('change', function () {
// Check that number entered into job priority stays within limits.
var value = Number(document.getElementById('job-priority').value);
var min = Number(document.getElementById('job-priority').min);
var max = Number(document.getElementById('job-priority').max);
if (value < min)
document.getElementById('job-priority').value = min;
else if (value > max)
document.getElementById('job-priority').value = max;
});
From my own research on this up to this point, I have come across one previous question post on StackOverflow regarding input patterns with input type number. That post, in short, confirms that input patterns don't work for input type number. It proposes the solution to just use input type text instead with a pattern to allow only numbers through. However, I want to keep the input type to number because of the up/down arrows that increase/decrease the number in the input field. I would be willing to change the input type to text only if their is a way to keep the up/down arrows in question.
I also see that if I remove the pattern from the input tag, my event listener for 'input' still successfully takes care of not allowing the 'e' '+' '-' characters somehow. Of course, the '.' symbol is still being allowed when it shouldn't. So I guess at least I confirmed that the pattern wasn't actually doing anything from what I can tell.
More specifically, if the '.' is typed as the first character, the validation check successfully works and nothing appears in the input field which is the desired behavior. However, if the first character typed is a number and then second character typed in is the '.' symbol, then for some reason the '.' symbol appears when it should not have.
Figured out a solution to my problem.
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
document.getElementById('job-priority').type = 'text';
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
document.getElementById('job-priority').type = 'number';
});
You'll see that what I did was change the input type to 'text' temporarily just for the input validation. Then, as soon as it's done, immediately change the input type back to 'number'.

Javascript regExp Input Validation

This is my first post and i think the answer is very easy but i don't get it:
I (try) to build a shopify store but i have to make some modifications and here is the point at where i am stuck:
On my Product Page i want to inluce a <input type=text>, which is required, can only be Capital Letters and the length must min. be 1 and max. 10. I tried it with html5 pattern but it didn't worked. I read something, that if the shopify theme includes ajax, it just ignores the pattern and the required attribute (i don't know if this is true).
So i tried to make my own functions:
$('#dein-text').on("change textInput input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase();
});
});
this just should return the string into capital letters.
function checkText() {
var re = /(?=.*[A-Z]).{1,6}/;
if(re.test($('#dein-text').val())) {
$('#problem-bei-input').hide();
$('.add', $product).removeClass('disabled').removeAttr('disabled');
} else {
$('#problem-bei-input').show();
$('.add', $product).addClass('disabled').attr('disabled', 'disabled');
}
}
this function is executed at every change on the input form:
$('#dein-text').on("change textInput input", checkText);
This does not work, because it removes the disabled class if there is min. 1 letter (it does not check if there are more than 6) and if there is one capital letter (something like "HA11" does not add the (.disabled) class).
i hope i could describe what my problem is.
Thank you for your help!
edit: this is the .liquid code of the whole form:
https://codepen.io/shawdyy/pen/PmOPWy
(i hope you can see this on codepen, sry i am really new to the webdev thing)
You can try:
$('#my_id').on("change input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase().replace(/[^A-Z]/, "").replace(/^([A-Z]{1,10}).*$/g, "$1");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_id">
To only allow one to ten uppercase ASCII letters in the input field use the following HTML5 pattern:
<input type="text" pattern="[A-Z]{1,10}" title="Only 1 to 10 uppercase ASCII letters allowed!">
If you need to match a string that only contains 1 to 10 uppercase ASCII letters in plain JS, you need
 var re = /^[A-Z]{1,10}$/;
Note that start and end anchors (^ / $) are added by the HTML5 automatIically when using the regex in the pattern attribute.

Determine if user is typing character by character or if more than 1 character is entered

I need to determine if a user is typing character by character into a text field or using browser autocomplete / pasting more than 1 character in javascript / jQuery.
I need to use the input method to determine the browser autocomplete:
$('input[type=text]').input(function(){
var a = this.value; // input value
var b = a.length; // amount of chars
$.each(a, function(i, j) {
// Loop through the input value each time after something is entered
}
});
I think I need the length of the last input value, so if it's = 1 typing is assumed or if it's more than 1 pasting / autocomplete is assumed.
Technically, 1 character can be pasted but no need to worry about that for now.
Thanks.
You'll need to handle the keyup event and track the length of the input string between the current keyup and the prior. If the difference in the string's length is greater than 1, then you know it was either the result of the auto-complete or pasted input.

Javascript function For Alpha Numeric in Asp.net [duplicate]

I have a textbox, and it needs not allow the user to enter any special characters. He can enter:
A-Z
a-z
0-9
Space.
One more condition is the first letter should be alphabetic.
How can I do a JavaScript verification on each keypress?
add a onKeyUp="javascript:checkChar(this);" to the input box.
function checkChar(tBox) {
var curVal = tBox.value;
if ( /[^A-Za-z0-9 ]/.test(curVal) ) {
//do something because he fails input test.
}
}
alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:
onKeyUp="javascript:checkChar(event);"
function checkChar(e) {
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;
if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
//fails test
}
}
missed the part about first char, but you can do a test on the textbox value as in the first example:
/^[A-Za-z]/.test(curVal)
or even use the second method but pass the text box as well so you can get it's full value.
This function will check the string given to it for those criteria:
function checkvalue(value) {
return value.match( /[A-Za-z][A-Za-z0-9 ]*/ );
}
You can then use that in an onkeypress event, passing in the current value.
Now that we have HTML5, you don't even need to use JavaScript. You can use the pattern attribute.
<input type="text" pattern="[A-Za-z][A-Za-z0-9 ]*" title="Description of format" />
The pattern attribute should contain a regular expression defining the format. And title should contain a human-readable description of the format.
Then on validation, depending on the browser, the browser will outline the field in red and/or display a message stating your description of the format.
This tutorial goes into more detail: HTML5 Input Validation Tutorial.
You should check pressed key in onkeydown event handler of the textbox and if it doesn't conform conditions then return false from the handler. Using keyup will not allow you to prevent char from being actually inputted in the textbox.
I don't think you should check on each keypress, it could be very annoying for the user.
Just check the input when it loses the focus, or when submiting.
To do it, you can use a regex and use this pattern:
`/[a-z]{1}[a-z0-9]/i`
You can also take a look at the JQuery Validation Plugin

Categories

Resources