Regex - Numeric regex with . and , - javascript

I have to create a regex that allows the user to input only a number (using . or ,)
so these examples are both valid:
8,5
8.5
here's my current code
private regex: RegExp = new RegExp(/^\d*[\,\.]{0,1}\d{1,2}/g);
However this allows me to input 8.,5 which is obviously bad. How can I change my regex so that the user can only place 1 of the decimal characters , OR .?
EDIT:
I've tried alot of answers, but most of them don't work (I can't place any decimal characters). Basically I'm creating a directive in angular that converts <input type="text"> to an numeric input (I can't use type="number")
Here's my directive code (see Angular2 - Input Field To Accept Only Numbers)
#Directive({
selector: "[OnlyNumber]"
})
export class OnlyNumberDirective {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^(?=.+)\d*(?:[\,\.]\d{1,2})?$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ["Backspace", "Tab", "End", "Home"];
constructor(private el: ElementRef) {
}
#HostListener("keydown", ["$event"])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
and here's how I use it in my template:
<mat-form-field class="numeric-textbox">
<input matInput
OnlyNumber
#model="ngModel"
placeholder="{{ label }}"
[ngModel]="selectedValue"/>
<mat-error><ng-content></ng-content></mat-error>
</mat-form-field>

You should specify the end of input string with $ without which a partial match will happen. You shouldn't look for \d* unless you want to match values like .5 or ,5 otherwise they will match as a valid input.
^\d+(?:[.,]\d{1,2})?$
Note: You don't need to escape dots or commas inside a character class and a quantifier like [.,]{0,1} is literally equal to [.,]?
Live demo:
document.getElementById("number").addEventListener("keyup",function(e) {
console.log(this.value.match(/^\d+(?:[.,]\d{1,2})?$/));
});
<input type="text" id="number" placeholder="Enter a number">
Update, based on comments
^(?![.,]?$)\d*[,.]?(?:\d{1,2})?$
This allows any number optionally followed or preceded by a decimal point or comma.
Live demo

The regex is correct, buy you just need to match the whole string:
^ start of the string
$ end of the string
However, the regex can be improved with:
^ : for start of string
\d+ : for at least 1 digit
(
[\,\.] : 1 comma
\d{1,2} : followed by 1 digit or two
)? : keep this optionnal. We can get numbers without commas
$ : end of string
Final regex may be:
/^\d+([\,\.]\d{1,2})?$/

Try: /^(?=.+)\d*(?:[,.]\d{1,2})?$/g
let regex = /^(?=.+)\d*(?:[,.]\d{1,2})?$/g,
strings = ["5", "50", "500", ".5", ",5","5.5","5,5", "5.55", "5,55", "5.555", "5,555", "5,,5", "5..5", "5,.5", "5.,5", "5,", "5."];
strings.forEach((string) => {
console.log(`${regex} ${string.match(regex) ? `matches ${string.match(regex)}`: `has no match for ${string}`}`);
});
This will match:
From the start, lookahead to make sure that there are characters present (one or more), and then begin matching: any amount of digits (0 or more), and the following optional: a comma or a dot, and then 1 or 2 digits before the end of the string.

Your regex is perfectly fine, you just need to specify the line's termination. You're currently matching 8 from 8,.5 which is likely why you're experiencing issues with your regex. I assume you're using JavaScript's test() function and getting true as a response for that string. Simply append $ to your regex and you'll get the correct answer. You can also simplify your regex to the following (also commented out in the snippet below). You can also probably drop the g flag as you're trying to match the string once, not multiple times:
^\d*[,.]?\d{1,2}$
What you're matching:
var a = ['8.5', '8,5', '.5', ',5', '8.,5']
var r = /^\d*[\,\.]{0,1}\d{1,2}/g
a.forEach(function(s){
console.log(s.match(r))
})
What you should be matching:
var a = ['8.5', '8,5', '.5', ',5', '8.,5']
var r = /^\d*[\,\.]{0,1}\d{1,2}$/g
// var r = /^\d*[,.]?\d{1,2}$/
a.forEach(function(s){
console.log(s.match(r))
})

Related

Javascript: GUID: RegEx: string to GUID

I have a textbox that a user can paste into using Ctrl+V. I would like to restrict the textbox to accept just GUIDs. I tried to write a small function that would format an input string to a GUID based on RegEx, but I can't seem to be able to do it. I tried following the below post:
Javascript string to Guid
function stringToGUID()
{
var strInput = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
var strOutput = strInput.replace(/([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/,"$1-$2-$3-$4-$5");
console.log(strOutput );
//from my understanding, the input string could be any sequence of 0-9 or a-f of any length and a valid giud patterened string would be the result in the above code. This doesn't seem to be the case;
//I would like to extract first 32 characters; how do I do that?
}
I suggest that you remove the dashes, truncate to 32 characters, and then test if the remaining characters are valid before inserting the dashes:
function stringToGUID()
{
var input = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
let g = input.replace("-", "");
g = g.substring(0, 32);
if (/^[0-9A-F]{32}$/i.test(g)) {
g = g.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
}
console.log(g);
}
stringToGUID();
(The i at the end of the regex makes it case-insensitive.)
You are already matching 32 characters with the pattern, so there is no need to get a separate operation to get 32 characters to test against.
You can replace all the hyphens with an empty string, and then match the pattern from the start of the string using ^
Then first check if there is a match, and if there is do the replacement with the 5 groups and hyphens in between. If there is not match, return the original string.
The function stringToGUID() by itself does not do anything except log a string that is hardcoded in the function. To extend its functionality, you can pass a parameter.
function stringToGUID(s) {
const regex = /^([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/;
const m = s.replace(/-+/g, '').match(regex);
return m ? `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` : s;
}
[
'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'b6b954d9-cbac-4b18-b0d5-a0f725695f1c',
'----54d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'!##$%'
].forEach(s => {
console.log(stringToGUID(s));
});

jQuery: Unable to use RegExp to search for exactly "+3.00" or "-3.00"

I'm struggling with finding the correct RegExp to match number with plus (+) or minus (-) sign at the end.
I have a select list of number ranging from 0.00- to 40.00- and 0.00+ to 40.00-. I'm using the following RegExp to filter out non matching records:
$("#MySelectBox").change(function() {
var filter = $(this).val()
// If the list item does not contain the numbers phrase fade it out
if ($(this).text().search(new RegExp('\\b'+filter+'\\b', "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
However, it will show both + and - numbers. For example: if filter = 3.00+ then it will return both 3.00+ and 3.00- values.
Any ideas how to get the exact match?
[\+-]\d{1,2}\.00
Will match + or -, followed by one or two digits (\d{1,2}), followed by .00.
However, RegExes don't have "greater than 40" kind of logic. They only match patterns.
There are useful tools to help you, like Rexegpal
So with your brief:
Check string matches pattern: "+xx.xx" or "-xx.xx"
Only numbers between -40 or +40
Omit results out of bounds
This could be a good way to achieve your desired result.
Notes: (1) Unsure if you wanted to enforce the demical point, (2) there are certainly multiple ways to achieve your result, this is is just one.
const regex = /^[\-\+]\d+\.*\d*$/;
const tests = ["41", "20", "+20", "-20", "+20.00", "-20.20", "20.20"];
const passedTests = tests.filter(number => {
const parsedNumber = Number.parseFloat(number);
const isValid = !!number.match(regex) && parsedNumber > -40 && parsedNumber < 40;
console.log(`Test ${number}, result: ${isValid}`);
return isValid;
});
console.log(passedTests);
To get an exact match for a number with plus (+) or minus (-) sign at the end and from 0.00- to 40.00- and 0.00+ to 40.00+, you can use:
^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$
^ Start of string
(?: Non capture group for the alternation |
(?:[0-9]|[123]\d) Match either a digit 0-9 or a number 10 - 39
\.\d\d Match a . and 2 digits 0-9
| Or
40\.00 Match 40.00
) Close group
[+-] Match either + or -
$ End of string
Regex demo
In Javascript you can use
const regex = /^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$/;
If the value is not the only value in the string, you could start with pattern with a word boundary \b and assert a whitespace boundary at the right (?!\S)
\b(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-](?!\S)
Regex demo

regex: remove leading zeros, but keep single zero

I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.
What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line. However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single). With .replace(/^0+/, '') it would remove every zero and return just an empty string. Someone knows what regex could handle this?
const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};
note: if(number === "") number = "0" is not an option.
edit1:: I noticed there seems to be a bit of confusion. e.g "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.
You ay use this regex replacement:
.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')
RegEx Demo
RegEx Details:
^: Start
(?:: Start capture group
0+(?=[1-9]): Match 1 or more zeroes that must be followed by 1-9
|: OR
0+(?=0$): Match 1 or more zeroes that must be followed by one 0 and end
): End capture group
Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.
Alternative solution using a capture group:
str = str.replace(/^0+(0$|[1-9])/mg, '$1');
A simple reg exp with leading zeros and match one digit in a capture group
const cleanZeros = str => str.replace(/^0+(\d)/, '$1')
var tests = ["0009876","0", "0000", "9999", "0090000"]
tests.forEach( s => console.log(s, cleanZeros(s)))

Javascript Regular Expression for numbers

I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");

RegEx for Javascript to allow only alphanumeric

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.
/^[a-z0-9]+$/i
^ Start of string
[a-z0-9] a or b or c or ... z or 0 or 1 or ... 9
+ one or more times (change to * to allow empty string)
$ end of string
/i case-insensitive
Update (supporting universal characters)
if you need to this regexp supports universal character you can find list of unicode characters here.
for example: /^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/
this will support persian.
If you wanted to return a replaced result, then this would work:
var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi, '');
console.log(b);
This would return:
Test123TEST
Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".
WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".
Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:
^\w+$
Explanation:
^ start of string
\w any word character (A-Z, a-z, 0-9, _).
$ end of string
Use /[^\w]|_/g if you don't want to match the underscore.
/^([a-zA-Z0-9 _-]+)$/
the above regex allows spaces in side a string and restrict special characters.It Only allows
a-z, A-Z, 0-9, Space, Underscore and dash.
^\s*([0-9a-zA-Z]*)\s*$
or, if you want a minimum of one character:
^\s*([0-9a-zA-Z]+)\s*$
Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.
The whitespace before and after is optional.
The parentheses are the grouping operator to allow you to extract the information you want.
EDIT: removed my erroneous use of the \w character set.
For multi-language support:
var filtered = 'Hello Привет 你好 123_456'.match(/[\p{L}\p{N}\s]/gu).join('')
console.log(filtered) // --> "Hello Привет 你好 123456"
This matches any letter, number, or space in most languages.
[...] -> Match with conditions
[ab] -> Match 'a' OR 'b'
\p{L} -> Match any letter in any language
\p{N} -> Match any number in any language
\s -> Match a space
/g -> Don't stop after first match
/u -> Support unicode pattern matching
Ref: https://javascript.info/regexp-unicode
This will work
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$
It accept only alphanumeriuc characters alone:
test cases pased :
dGgs1s23 - valid
12fUgdf - valid,
121232 - invalid,
abchfe - invalid,
abd()* - invalid,
42232^5$ - invalid
or
You can also try this one. this expression satisfied at least one number and one character and no other special characters
^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$
in angular can test like:
$scope.str = '12fUgdf';
var pattern = new RegExp('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$');
$scope.testResult = pattern.test($scope.str);
PLUNKER DEMO
Refered:Regular expression for alphanumeric in Angularjs
Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.
/[^a-z\d]/i
Here is an example:
var alphanumeric = "someStringHere";
var myRegEx = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));
Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.
I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)
Below is what i did:
string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()
Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.
I ended up getting something like this:
samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.
There might be a better solution but this is what i found working fine for me.
Extend the string prototype to use throughout your project
String.prototype.alphaNumeric = function() {
return this.replace(/[^a-z0-9]/gi,'');
}
Usage:
"I don't know what to say?".alphaNumeric();
//Idontknowwhattosay
Even better than Gayan Dissanayake pointed out.
/^[-\w\s]+$/
Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$
You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.
Input these code to your SCRATCHPAD and see the action.
var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
JAVASCRIPT to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS
document.getElementById("onlynumbers").onkeypress = function (e) {
onlyNumbers(e.key, e)
};
document.getElementById("onlyalpha").onkeypress = function (e) {
onlyAlpha(e.key, e)
};
document.getElementById("speclchar").onkeypress = function (e) {
speclChar(e.key, e)
};
function onlyNumbers(key, e) {
var letters = /^[0-9]/g; //g means global
if (!(key).match(letters)) e.preventDefault();
}
function onlyAlpha(key, e) {
var letters = /^[a-z]/gi; //i means ignorecase
if (!(key).match(letters)) e.preventDefault();
}
function speclChar(key, e) {
var letters = /^[0-9a-z]/gi;
if ((key).match(letters)) e.preventDefault();
}
<html>
<head></head>
<body>
Enter Only Numbers:
<input id="onlynumbers" type="text">
<br><br>
Enter Only Alphabets:
<input id="onlyalpha" type="text" >
<br><br>
Enter other than Alphabets and numbers like special characters:
<input id="speclchar" type="text" >
</body>
</html>
A little bit late, but this worked for me:
/[^a-z A-Z 0-9]+/g
a-z : anything from a to z.
A-Z : anything from A to Z (upper case).
0-9 : any number from 0 to 9.
It will allow anything inside square brackets, so let's say you want to allow any other character, for example, "/" and "#", the regex would be something like this:
/[^a-z A-Z 0-9 / #]+/g
This site will help you to test your regex before coding.
https://regex101.com/
Feel free to modify and add anything you want into the brackets.
Regards :)
It seems like many users have noticed this these regular expressions will almost certainly fail unless we are strictly working in English. But I think there is an easy way forward that would not be so limited.
make a copy of your string in all UPPERCASE
make a second copy in all lowercase
Any characters that match in those strings are definitely not alphabetic in nature.
let copy1 = originalString.toUpperCase();
let copy2 = originalString.toLowerCase();
for(let i=0; i<originalString.length; i++) {
let bIsAlphabetic = (copy1[i] != copy2[i]);
}
Optionally, you can also detect numerics by just looking for digits 0 to 9.
Try this... Replace you field ID with #name...
a-z(a to z),
A-Z(A to Z),
0-9(0 to 9)
jQuery(document).ready(function($){
$('#name').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
Save this constant
const letters = /^[a-zA-Z0-9]+$/
now, for checking part use .match()
const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
if (string[i].match(letters) ) {
id += string[i]
} else {
// In case you want to replace with something else
id += '-'
}
}
return id
Alphanumeric with case sensitive:
if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
alert("match")
}
Also if you were looking for just Alphabetical characters, you can use the following regular expression:
/[^a-zA-Z]/gi
Sample code in typescript:
let samplestring = "!#!&34!# Alphabet !!535!!! is safe"
let regex = new RegExp(/[^a-zA-Z]/gi);
let res = samplestring.replace(regex,'');
console.log(res);
Note: if you are curious about RegEx syntax, visit regexr and either use the cheat-sheet or play with regular expressions.
Edit: alphanumeric --> alphabetical
Only accept numbers and letters (No Space)
function onlyAlphanumeric(str){
str.value=str.value.replace(/\s/g, "");//No Space
str.value=str.value.replace(/[^a-zA-Z0-9 ]/g, "");
}
<div>Only accept numbers and letters </div>
<input type="text" onKeyUp="onlyAlphanumeric(this);" >
Here is the way to check:
/**
* If the string contains only letters and numbers both then return true, otherwise false.
* #param string
* #returns boolean
*/
export const isOnlyAlphaNumeric = (string: string) => {
return /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/.test(string);
}
Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Enter Only Numbers:
<input type="text" id="onlynumbers">
<br><br>
Enter Only Alphabets:
<input type="text" id="onlyalpha">
<br><br>
Enter other than Alphabets and numbers like special characters:
<input type="text" id="speclchar">
<script>
$('#onlynumbers').keypress(function(e) {
var letters=/^[0-9]/g; //g means global
if(!(e.key).match(letters)) e.preventDefault();
});
$('#onlyalpha').keypress(function(e) {
var letters=/^[a-z]/gi; //i means ignorecase
if(!(e.key).match(letters)) e.preventDefault();
});
$('#speclchar').keypress(function(e) {
var letters=/^[0-9a-z]/gi;
if((e.key).match(letters)) e.preventDefault();
});
</script>
</body>
</html>
**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **
<!DOCTYPE html>
$('#onlynumbers').keypress(function(e) {
var letters=/^[0-9]/g; //g means global
if(!(e.key).match(letters)) e.preventDefault();
});
$('#onlyalpha').keypress(function(e) {
var letters=/^[a-z]/gi; //i means ignorecase
if(!(e.key).match(letters)) e.preventDefault();
});
$('#speclchar').keypress(function(e) {
var letters=/^[0-9a-z]/gi;
if((e.key).match(letters)) e.preventDefault();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
Enter Only Numbers:
Enter Only Alphabets:
Enter other than Alphabets and numbers like special characters:
</body>
</html>

Categories