Javascript Regular Expression for allowing multiple phone numbers in text box - javascript

I have a text box in which i want user to provide multiple mobile numbers, each number should be only 10 digits and they should be comma separated. Other than comma no special character should be allowed not even space.

I'll assume you can figure out how to get the value out of the textbox.
Here's a regex that'll do the number validation:
/^(\d{10}(,\d{10})*)?$/
This will allow the field to be blank, but if something is entered it would have to be one or more 10-digit numbers separated by commas.

Instead of finding one regular expression for the whole thing, you could just split it up and test an expression for each segment, drop the bad ones and stitch the thing back together. This way you can theoretically match hundreds of phone numbers :)
var numbers = 'aaa,456,789'.split(',').filter(function(item) {
return /^\d{10}$/.test(item)
});
if (numbers.length > 2) {
// too many numbers?
} else if (!numbers.length) {
// no numbers?
}
// this will give you back a comma separated list in a string
// numbers.join(',')
Note that Array.filter() may not work on evil all browsers, so you'd have to find a suitable alternative for that.

You can do this
/^\d{10}(,\d{10})*$/
\d{10} matches 10 digits
(,\d{10})* matches , and 10 digits 0 to many times

A validation function for your phonenumbers. If the field is left empty this validates to true.
function validateNumbers( text ) {
var numbers = text.split(",");
for( var i = 0, len = numbers.length; i < len; i++ ) {
if( !/^\d{10}$/.test( numbers[i] ) ) {
return false;
}
}
return true;
}

Similar to others, but without having to repeat the \d{10} part
^(?:\d{10},?\b)+$

Use one of the following regex patterns:
/^(\d{10}(,(?=.))?)+$/
/^(\d{10}(,(?=.)|$))+/
/^(\d{10}(,(?=.)|))+$/
/^\d{10}(,\d{10})*$/

Related

Using javascript or python regular expressions I want to determine if the number is 1-99 how to make it?

var category = prompt("where do you go? (1~99)", "");
hello
Using regular expressions I want to determine if the category is 1-99.
How can I solve it?
Thank you if you let me know.
You can use character classes to match digits, like this [0-9]. If you put two of them together you'll match 00 - 99. If you put a ? after one of them, then it's optional, so you'll match 0 - 99. To enforce 1-99, make the non-optional one like this [1-9]. Finally, you need to make sure there's nothing before or after the one or two digits using ^, which matches the beginning of the string, and $ which matches the end.
if (category.match(/^[1-9][0-9]?$/)){
console.log("ok")
} else {
console.log("not ok")
}
In JavaScript you can use test() method with RE for 1-99 as shown below:
var one_to_ninetynine = /^[1-9][0-9]?$/i;
if(one_to_ninetynine.test(category)) {
console.log("The number is between 1-99");
} else {
console.log("The number is NOT between 1-99");
}

JS - Iterate through text snippet character by character, skipping certain characters

I am using JS to loop through a given text, refered to in below pseudo as "input_a".
Based on the contents of another, and seperate text "input_b" I would like to manipulate the individual characters of text "input_a" by assigning them with a boolean value.
So far I've approached it the following way:
for (i=0; i < input_a.length; i++) {
if (input_b[i] == 0){
//do something to output
}
}
Now the issue with this is that the above loop, being that it uses .length also includes all blank/special characters whereas I would only like to include A-Z - ommitting all special characters (which in this case would not be applicable to recieve the boolean assigned to them).
How could I approach this efficiently and elegantly - and hopefully without reinventing the wheel or creating my own alphabet array?
Edit 1: Forgot to mention that the position of the special characters needs to be retained when the manipulated input_a is finally delivered as output. This makes an initial removal of all special characters from input_a a non viable option.
It sounds like you want input_a to retain only alphabetical characters - you can transform it easily with a regular expression. Match all non-alphabetical characters, and replace them with the empty string:
const input_a = 'foo_%%bar*&#baz';
const sanitizedInputA = input_a.replace(/[^a-z]+/gi, '');
console.log(sanitizedInputA);
// iterate through sanitizedInputA
If you want the do the same to happen with input_b before processing it, just use the same .replace that was used on a.
If you need the respective indicies to stay the same, then you can do a similar regular expression test while iterating - if the character being iterated over isn't alphabetical, just continue:
const input_a = 'foo_%%bar*&#baz';
for (let i = 0; i < input_a.length; i++) {
if (!/[a-z]/i.test(input_a[i])) continue;
console.log(input_a[i]);
}
You can check if the character at the current position is a letter, something like:
for (i=0; i < input_a.length; i++) {
if(/[a-z]/i.test(input_a[i])){
if (input_b[i] == 0){
//do something to output
}
}
}
the /[a-z]/i regex matches both upper and lower case letters.
Edited as per Edit 1 of PO
If you would like to do this without RegEx you can use this function:
function isSpecial(char) {
if(char.toLowerCase() != char.toUpperCase() || char.toLowerCase.trim() === ''){
return true;
}
return false;
}
You can then call this function for each character as it comes into the loop.

How to remove the first character from a string if it's a non-number in JavaScript?

I have a text field on a form that allows individuals to enter a price. I'm trying to allow other currency symbols to be entered into this field but my logic behind the scenes needs to strip out any currency symbols.
To make it easier, I really only care about the first character and only if it's a non number.
Otherwise, I can't use a solution that would remove any decimal points or commas in my price field or my calculations won't work.
Update: I'm currently using
itemCost = itemCost.replace(/\$/, '');
But now I'm trying to open it up to any currency sign.
You can access a string in the same way as you would an array. Take a look at the character at position zero of the string -
var inputString = '...' // whatever the user entered
var firstChar = inputString[0];
if (!Number.isInteger(firstChar)) {
inputString = inputString.substr(1)
}
I'm using the String.subStr function here to create a copy of the string starting from the 1st index.
Please take into consideration though that solution assumes that the provided string will only ever have one currency symbol. Inputs such as "USD $1.00" or even " $1.00" will not work with this solution.
An alternative would be to remove any character that is non numeric (excluding decimal points and commas) from the entire input string.
var inputString = '...' // whatever the user entered
var priceString = inputString.replace(/[^0-9\.,]/, '')
// $1.00 -> 1.00
// USD #$1,000.00 -> 1,000.00
Why don't you whitelist characters instead?
'$99,99'.match(/[0-9]+[,.]{0,1}[0-9]*/)
You'll certainly want to perfect it, I wrote it fast...
What the suggested regex does is make sure we have one or more digits, then maybe either a , or a . and 0 or more digits.
What I mostly want to point out with this answer is, while keeping just numeric characters is easy, it will by no mean make certain that the user entered a correct currency. The is also no way to know if the user entering 1,337 meant 1,337.00 or 1.337
There's a few ways you can do this... One way is to make the input into an array, check isNaN on the first element, and strip it if it's not a number.
const input = '$123.45';
const otherInput = '23.34';
function splitCheck(someInput) {
let arrayInput = someInput.split('');
if (isNaN(arrayInput[0])) {
arrayInput.shift();
return arrayInput.join('');
} else {
return someInput;
}
}
splitCheck(input); // returns 123.45
splitCheck(otherInput); // returns 23.34
Note you can also use a regexp, or you can also check for ASCII character values across an array, but this is just the first that came to mind.
A Javscript function could be
// Function to check first letter as numbers
function chkNumeric(inputtxt)
{
var letterNumber = '^[0-9]{1,}[ a-zA-Z0-9]*$';
if((inputtxt.value.match(letterNumber))
{
return true;
}
else
{
return false;
}
}
You may use parseInt()
parseInt() parses a string and returns an integer.
If the first character cannot be converted to a number, parseInt() returns NaN.
parseInt('Hello') // returns NaN
Also it's a good idea to trim() the string before using parseInt()
var money = '$123.45';
if( money ) { // check if variable is not null
money = money.trim();
}
console.log(parseInt(money));
// check NaN using isNaN function
if(isNaN(parseInt(money))) {
console.log('first charatcer is not a number')
money = money.substr(1);
console.log(money);
}
else {
console.log('first charatcer is a number')
}

Regex for validation

Can anyone tell me how to write a regex for the following scenario. The input should only be numbers or - (hyphen) or , (comma). The input can be given as any of the following
23
23,26
1-23
1-23,24
24,25-56,58-40,45
Also when numbers is given in a range, the second number should be greater than the first one. 23-1 should not be allowed. If a number is already entered it should not be allowed again. Like 1-23,23 should not be allowed
I'm not going to quibble with "I think" or "maybe" -- you can not do this with a Regex.
Matching against a regex can validate that the form of the input is correct, and can also be used to extract pieces of the input, but it can not do value comparisons, or duplicate elimination (except in limited well defined circumstances), or range checking.
What you have as input I interpret as a comma-separated list of values or ranges of values; in BNFish notation:
value :: number
range :: value '-' value
term :: value | range
list :: term [','term]*
A regex can be built that will match this to verify correct structure, but you'll have to do other validation for the value comparisons and to prevent the duplicate numbers.
The most straigtforward regex I can think of (on short notice) is this
([0-9]+|[0-9]+-[0-9]+)(, *([0-9]+|[0-9]+-[0-9]+))*
You have digits or digits-digits, optionally followed by comma[optional space](digits or digits-digits) - repeated zero or more times.
I tested this regex at http://www.fileformat.info/tool/regex.htm with the input 3,4-12,6,2,90-221
Of course you can replace the [0-9] with [\d] for regex dialects that allow it.
var str = "24,25-56,24, 58- 40,a 45",
trimmed = str.replace(/\s+/g, '')
//test for correct characters
if (trimmed.match(/[^,\-\d]/)) alert("Please use only digits and hyphens, separated by commas.")
//test for duplicates
var split = trimmed.split(/-|,/)
split.sort()
for (var i = 0; i < split.length - 1; i++) {
if (split[i + 1] == split[i]) alert("Please avoid duplicate numbers.")
}
//test for ascending range
split = trimmed.split(/,/)
for (var i in split) {
if (split[i].match("-") && eval(split[i]) < 0) alert("Please use an ascending range.")
}
I don't think you will be able to do this with a RegEx. Especially not the part about set logic - number already used, valid sequential range.
My suggestion would be to have a Regex verify the format, at the least -, number, comma. Then use the split method on commas and loop over the input to verify the set. Something like:
var number_ranges = numbers.split(',');
for (var i = 0; i < number_ranges.length; ++i) {
// verify number ranges in set
}
That logic is not exactly trivial.
I think with regular expressions it is better to take the time to learn them than to throw someone elses script into yours without knowing exactly what it is doing. You have excellent resources out there to help you.
Try these sites:
regular-expressions.info
w3schools.com
evolt.org
Those are the first three results form a google search. All are good resources. Good luck. Remember to double check what your regex is actually matching by outputing it to the screen, don't assume you know (that has bitten me more than one time).

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources