I wanted to do an input with that numbers but I do not arrive if I put the type of input to text I can put 5 character alpha numeric and if I put the type of input to number I can put only numbers but it is not limited to 5 numbers
Thank you all
HTML
<input type="text" id="number" name="postalCode" placeholder="Saisissez le code postal" formControlName="postalCode" maxlength="5" class="a-textbox" pattern="/^(([0-8][0-9])|(9[0-5]))[0-9]{3}$/" />
Angular
postalCode: new FormControl('', [Validators.maxLength(5)]),
You can try this solution
I have create a demo on stackblitz
html code
<input type="text" OnlyNumber id="number" name="postalCode" placeholder="Saisissez le code postal" formControlName="postalCode" maxlength="5" class="a-textbox" />
OnlyNumber attribute directive
import { Directive, ElementRef, HostListener } from '#angular/core';
#Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumberDirective {
constructor(private el: ElementRef) { }
#HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
let e = <KeyboardEvent>event;
/*
8 - for backspace
9 - for tab
13 - for enter
27 - for escape
46 - for delete
*/
if ([8, 9, 13, 27, 46].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+C
(e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+V
(e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+X
(e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
#HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.validateFields(event);
}
validateFields(event) {
setTimeout(() => {
let numberRegEx = /^[0-9]+$/;
if(!numberRegEx.test(this.el.nativeElement.value)){
this.el.nativeElement.value = "";
event.preventDefault();
}
}, 100)
}
}
This directive worked very well for me and has everything that you need to force it to 5 digits only and to exclude number related characters such as period, "e", etc.
I recommend to keep the input as type text, as well, see reasoning here.
Digit Only Directive in Angular
Angular DigitOnly Directive and Mask Directive
https://github.com/changhuixu/ngx-digit-only
Related
Angular4 docs shows ( Key event filtering (with key.enter) ) how to catch keyboard keystrokes events easier - (keyup.enter)="foo()" or keyup.w or keyup.space etc.
What I need is to fire event only if letters being pressed.
One way I can think of is:
<input id="textFilter" (keyup)=“foo($event)”>
foo(e){
var allowedKeys = [‘KeyQ’, ‘KeyW’, ‘KeyE’, and the rest of the alphabet...]
if (allowedKeys.indexOf(e.code) != -1 ) {
return true;
}
}
But I would expect such pseudo-events already build-in in Angular. For ex. for letters, like - (keyup.letters)="foo()" and for numbers, like -(keyup.numbers)="foo()". Are there any? And is that solution above is preferable for filtering keyboard keystrokes by groups?
docs
I appreciate any help.
AFAIK there are no keyup groups provided by angular. But you can easily create custom directive to allow/disallow your own set of keys.
Here's a demo of allowing letters only.
only-letters.directive.ts:
import { Directive, ElementRef, HostListener, Input } from '#angular/core';
#Directive({
selector: '[onlyLetters]'
})
export class OnlyLetters {
constructor(private el: ElementRef) { }
#Input() onlyLetters: boolean;
#HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if (this.onlyLetters) {
// console.log(e);
if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if (((e.keyCode < 65 || e.keyCode > 90)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
}
}
I would like to create 3 input fields just like the ones on any Shopify checkout page.
Here are the functions for the input fields:
making spaces every 4 digits in the credit card number input field; number-only field; limiting it to 16 characters
creating a slash in after 2 digits for the expiration date field; limiting it to 8 characters; number-only field
This one would allows the user to do 2 things:
Write a number from 2-9, which automatically writes a slash afterwards.
It should look like this.
Write either 10, 11, or 12, which automatically writes a slash afterwards.
It should look like this.
See how it writes a slash automatically right after the second number? It only does that if you type in "/" or a second number for the month.
Here is what I'm playing with:
/*$('#number').on('keypress',function(){
var val = this.value;
var firstVal = val.slice(0,2);
var secondVal = val.slice(2,6);
var finalVal = firstVal+"/"+secondVal;
console.log(finalVal);
this.value = finalVal;
}); */
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
$(document).ready(function() {
$("#number").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl/cmd+A
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl/cmd+C
(e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl/cmd+X
(e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
But the problem I'm having here is that you can't even type a slash.
Thanks in advance,
Josiah
I'm using this code for validating the phone number:
<script>
$("#Phone").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
var val = Phone.value
if (/^\d{11}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be eleven digits")
Phone.focus()
return false
}
</script>
I want the user to input only 11 digits and if it doesn't, it alerts user that they have to input 11 digits and sets the value to null.
The problem is, when it alerts that the number is less than 11 digits, it doesn't set the value to null.
I know you're asking for a JS solution but this can be done with the new attributes in html5
<input type="tel" pattern="[0-9]{11}" placeholder="Your 11 digit phone number..." required/>
Fiddle here: https://jsfiddle.net/7owhrssr/
This code can help you, cause may you have problem with regex
var regex =/^\d+$/;
if (regex.test(val)) {
alert('value is ok, use it');
}else{
alert('Invalid number; must be eleven digits');
Phone.focus()
return false}
How do I restrict input fields to numeric values rather than integer values?
<input type="text" class="numericOnly">
jQ
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
Try this
$(".numericOnly").keypress(function(e) {
var code = e.which;
if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 51) || (code == 8) || (code >= 37 && code <= 40))
{
return true;
}
return false;
})
.bind("paste",function(e) {
e.preventDefault();
});
If you want to allow decimal points, add them to the character class you're using. E.g. /[^0-9.]/g if a decimal point in your locale is ., or /[^0-9,]/g if it's , (as it is in some).
Of course, that would let someone type .0.0.0.1, you'll want whole-value checks on the field as well as keystroke-level checks.
Separately, remember there are lots of ways for values to get into fields other than typing (pasting, for instance), so (again) whole-value checks at some stage will be a good idea.
Side note: Use e.which, not e.keyCode. jQuery normalizes the event object, setting e.which on browsers that don't set it natively.
With Dot
Get this js file
http://thefitties.co.uk/js/plugins/jquery-numeric.js
And
In HTML
<input class="numeric" type="text">
in Script
$("input.numeric").numeric()
WITHOUT DOt
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
OR
http://jsfiddle.net/lesson8/HkEuf/1/
I found this very short clean code to only allow numeric chars in a text field. Currently it only covers numbers 0-9 and backspace and delete. I wanted it to also include decimal/period, so I have been fighting with this to simply include keycode 110 and/or 190. I can not get it to work. Can anyone see what I am doing wrong?
$(document).ready(function() {
$('input.numberinput').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) || (e.which!=110) ? false : true ;
});
});
jsfiddle here: http://jsfiddle.net/justmelat/EN8pT/
html
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
</div>
Try:
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
return !(e.which != 8 && e.which != 0 &&
(e.which < 48 || e.which > 57) && e.which != 46);
});
});
JsFiddle: http://jsfiddle.net/EN8pT/1/
With the above answer you can still do 0.23.12.33 which is not a valid number.
http://www.texotela.co.uk/code/jquery/numeric/ is a great little lightweight plugin that I have used a lot. It takes the pain out of the above.
$("#input").keydown(function(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
// Allow: backspace, delete, tab, escape, and enter
if ( key == 46 || key == 8 || key == 9 || key == 27 || key == 13 || key == 110 || key == 190 ||
// Allow: Ctrl+A
(key == 65 && theEvent.ctrlKey === true) ||
// Allow: home, end, left, right
(key >= 35 && key <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (theEvent.shiftKey || (key < 48 || key > 57) && (key < 96 || key > 105 )) {
theEvent.preventDefault();
}
}
});
with keycode 110 and 190