Allowing a dash in this regex - javascript

I'm using this Wordpress plugin called 'Easy contact form' which offers standard validation methods.
It uses the following regex for phone numbers:
/^(\+{0,1}\d{1,2})*\s*(\(?\d{3}\)?\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/
Just now it allows the following formats (maybe more):
0612345678
+31612345678
But I want it to allow +316-12345678 and 06-12345678 also ... Is this possible? If so, how?
Thanks in advance!

You can use a less complex regex :
^\+?\d{2}(-?\d){8,9}$
This regex allows a + at the beginning of the phone number, then matches two digits, and after that, digits preceded (or not) by a -, for a total of 10 or 11 digits.
Now you can adapt it if the initial + is only for 11-digits phone numbers :
^\+?\d{3}(-?\d){9}|\d{2}(-?\d){8}$
My regex allow you to use - every digit. If that's an issue, it can be changed :
^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$
I think this last regex will answer your needs, and it's quite simple !

When you figure out what patterns you actually want to allow and not allow. Then fill them out in this function and if the statement returns true you have your regex.
var regex = /^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$/; //this is your regex, based on #Theox third answer
//allowed patterns
['0612345678', '+31612345678', '+316-12345678', '06-12345678'].every(function(test) {
return regex.exec(test) !== null;
}) &&
//disallowed patterns, none right now
[].every(function(test) {
return regex.exec(test) === null;
});

Related

JavaScript regex inline validation for basic calculation string with one operator

I've written a basic 2 operand calculator app (+ - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed.
An example looks like:
//check if operator is present
if(/[+\-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
if(!/^\d+\.?\d*[+\-*\/]?\d*\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
//validate the string character by character before operator
} else {
if(!/^\d+\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
}
In the above, a valid character doesn't return false:
23.4x0.00025 (no false returned and hence the string is typed out)
But, if an invalid character is typed the function returns false and the input is filtered away:
23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)
23.4x0. is typed
It works pretty well but allows for the following which I would like to deal with:
2.+.1
I would prefer 2.0+0.1
My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [+-*/] then the next character must be a number, else the next char can be any char (while following the overall logic).
The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.
if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.
Any suggestions about this specific problem would be really helpful.
Thanks
https://github.com/jdineley/Project-calculator
Thanks #trincot for the tips using capturing groups and look around. This helped me write what I needed:
https://regex101.com/r/khUd8H/1
git hub app is updated and works as desired. Now just need to make it pretty!
For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)
Demo:
const validate = s => /^(\d+(\.\d*)?((?<=\d)[+*/-]|$))*$/.test(s);
document.querySelector("input").addEventListener("input", function () {
this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
Input: <input>

Formatting in Javascript

I have a question related to formatting strings.
User should parse a string in the Format XX:XX.
if the string parsed by user is in the format XX:XX i need to return true,
else false:
app.post('/test', (req, res) => {
if (req.body.time is in the format of XX:XX) {
return true
} else {
return false
}
});
You can use the RegExp.test function for this kind of thing.
Here is an example:
var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);
The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.
Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.
The tool you're looking for is called Regular Expressions.
It is globally supported in almost every development platform, which makes it extremely convenient to use.
I would recommend this website for working out your regular expressions.
/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:
[a-zA-Z]{2} - two characters from the sets a-z and A-Z.
Followed by :
Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.
^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.
try using regex
var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){ //if true
//do something
}
else{}

Combine whitelist and blacklist in javascript regex expression

I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: _ and ?
So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]
I need to combine these into one expression.
I have tried the following code, but does not work the way I had hoped:
var input = "this%";
var patrn = /[^\u0000-\uFFFF&&[^_%]]/g;
if (input.match(patrn) == "" || input.match(patrn) == null) {
return true;
} else {
return false;
}
input: this%
actual output: true
desired output: false
If I understand correctly, one of these should be enough:
/^[^_%]*$/.test(str);
!/[_%]/.test(str);
Use negative lookahead:
(?!_blacklist_)_whitelist_
In this case:
^(?:(?![_%])[\u0000-\uFFFF])*$
Underscore is \u005F and percent is \u0025. You can simply alter the range to exclude these two characters:
^[\u0000-\u0024\u0026-\u005E\u0060-\uFFFF]
This will be just as fast as the original regex.
But I don't think that you are going to get the result you really want this way. JS can only go up to \uFFFF, anything past that will be two characters technically.
According to here, the following code returns false:
/^.$/.test('💩')
You need to have a different way to see if you have characters outside that range. This answer gives the following code:
String.prototype.getCodePointLength= function() {
return this.length-this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length+1;
};
Simply put, if the number returned by that is not the same as the number returned by .length() you have a surrogate pair (and thus you should return false).
If your input passes that test, you can run it up against another regex to avoid all the characters between \u0000-\uFFFF that you want to avoid.

Number extraction from string using regex working partially

I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript.
Here's the regex pattern I am using:
var numberPattern = /^9[0-9]{9}/;
Here's the pattern matching phase:
var numberstring = JSON.stringify(data[i].text);
if(numberPattern.test(data[i].text.toString()) == true){
var obj={
tweet : {
status : data[i].text
},
phone : numberstring.match(numberPattern)
}
//console.log(numberstring.match(numberPattern));
stringarray.push(obj);
The problem is it is working for few numbers and not all. Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. I'm a beginner in regex, so help is needed. Thanks.
Example:
#Chennai O-ve blood for #arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via #arun_scribbles
Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/.
To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\+?(9|8)[0-9]{9}/.
To allow any character except "0", replace the (9|8) with a construct to accept only 1-9: /^\+?[1-9][0-9]{9}/.
And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. If you're looking for content in the middle of the line, you'll need to drop the caret: /\+?[1-9][0-9]{9}/.
var numberPattern = /([+]91)?9[0-9]{9}\b/;
Try this regex pattern: [\+]?[0-9]{1,4}[\s]?[0-9]{10}
It accepts any country code with +, a space, and then 10 digit number.

What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules...
it will include 10 digits
if there is a leading 1 or +1 it should be ignored
valid characters allowed in the field are... 0-9,(), and -
I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^adfafsd. I believe the error is in my code not the regex. For example, are there supposed to be quotes around the expression?
Here is the code that is supposed to be validating the phone field...
$('#phone').bind('blur', function() {
var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
if(pattern.test($('#phone').val())){
$("#phone").addClass("error");
return false;
}else{
$("#phone").removeClass("error");
return true;
}
return true;
})
When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. Try this instead:
var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;
if(regex.test($('#phone').val()){ ... }
if there is a leading 1 or +1 it should be ignored
it will include 10 digits
valid characters allowed in the field are... 0-9,(), and -
That could be matched with an expression like:
/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/

Categories

Resources