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

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}$/

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>

JS - Nothing to repeat In match function

The error is simple. In JS I try to do somtehing to similar a preg_match in PHP. I found match function. I use this function to compare a value with strings elements. If found something return true, else return false.
I tried this
var sim_action = $(this);
if(sim_action.data("phone").toString().match("/^(+34|0034|34)+([67]){8})$/")){
But return this error.
Invalid regular expression: //^(+34|0034|34)+([67]){8})$//: Nothing
to repeat
So the question is. How can i add this string in JS match function?
You need to escape the + characters with a backslash: /^(\+34|0034|34)\+([67]){8})$/. You also have a closing bracket which doesn't have a matching opening bracket.
+ and () are metacharacters and if you want to refer to the literal, you need to escape them with a \. Here's a regex101 demo which highlights the errors with your regex
As for the regex, from wikipedia, I gather that spanish phone numbers have the format +34(6|7)xxxxxxxx
You can use this regex: /^(\+34|0034|34)[67]\d{8}$/
If you just want to check if the regex passes , you can use regex.test(<stringToBeTested>)
const regex = /^(\+34|0034|34)[67]\d{8}$/
const phone = "+34712345673";
if (regex.test(phone))
console.log("Valid phone number")
const phoneNumbers = ["+34712345673", "0034612345673", "+34812345673"]
phoneNumbers.forEach(p => console.log(regex.test(p)))

Allowing a dash in this regex

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;
});

syntax error on function to detect non-alphanumeric characters in a value?

I know that there are hundreds( or likely thousands) of questions regarding regex functions in this forum. I have read and consulted several, and by all presumptions, I ought to have the answer, and my function ought to work, but it isn't.
I have tried to build a function, in which one of the checks is for only allowing alpha-numeric characters.
The abridged version of the code is this:
function functionName() {
var x = $("#inputId").val();
//trying to locate any/all non alphanumeric characters & spaces
var regex = /^[^0-9a-zA-Z\s]+$/g
if ( x.indexOf(regex) >= 0 ){
alert("message");
return false;
}
}
Does anyone know where I am going wrong?
Thanks
You shouldn't be using indexOf; you should be using test. That's also a little bit of a funny regex you're using. I've modified it below to match valid strings instead of invalid.
function functionName(){
var x = $("#inputId").val();
var regex = /^[a-zA-Z0-9]+$/g;
if ( x.test(regex) ){
alert("Only contains alphanumeric characters. No punctuation or spaces!");
} else {
return false;
}
}
You regex matches only strings that consist entirely of invalid characters. What you really want is one matching when there is at least one invalid character
var regex = /[^0-9a-zA-Z\s]/;
if (regex.test(x)) ...
Your are missing the final '}'

Regex to validate a password [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}
Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.
You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])
Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.
What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.

Categories

Resources