I want to allow my users to enter a phone number and choose their own way of seperating the numbers (or not). So I came up with a regex:
var regex = /[^0-9 \/-\\\(\)\+]/;
In most cases it works fine, but there are some examples like #,:,; where it doesn't work as I would expect. Could someone give me some hint please ?
Here's an example of what I mean
testvar = '123#213';
var regex = /[^0-9 \/-\\\(\)\+]/;
if(regex.test(testvar) === true)
{ alert('Chars out of regex-range found'); } // won't fire!
There's a long way from / to \ if you meant it. And if not, you're missing a slash before the dash:
var regex = /[^0-9 \/\-\\\(\)\+]/;
A phone number only uses digits, I'd ignore the user format and just keep the digits
var phonenum=value.replace(/\D+/g,'');
Related
I want to match the First url followed by a space using regex expression while typing in the input box.
For example :
if I type www.google.com it should be matched only after a space followed by the url
ie www.google.com<SPACE>
Code
$(".site").keyup(function()
{
var site=$(this).val();
var exp = /^http(s?):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
var find = site.match(exp);
var url = find? find[0] : null;
if (url === null){
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?/g;
var find = site.match(exp);
url = find? 'http://'+find[0] : null;
}
});
Fiddle
Please help, Thanks in advance
you should be using a better regex to correctly match the query & fragment parts of your url. Have a look here (What is the best regular expression to check if a string is a valid URL?) for a correct IRI/URI structured Regex test.
But here's a rudimentary version:
var regex = /[-\w]+(\.[a-z]{2,})+(\/?)([^\s]+)/g;
var text = 'test google.com/?q=foo basdasd www.url.com/test?q=asdasd#cheese something else';
console.log(text.match(regex));
Expected Result:
["google.com/?q=foo", "www.url.com/test?q=asdasd#cheese"]
If you really want to check for URLs, make sure you include scheme, port, username & password checks just to be safe.
In the context of what you're trying to achieve, you should really put in some delay so that you don't impact browser performance. Regex tests can be expensive when you use complex rules especially so when running the same rule every time a new character is entered. Just think about what you're trying to achieve and whether or not there's a better solution to get there.
With a lookahead:
var exp = /[-\w]+(\.[a-z]{2,})+(\S+)?(\/|\/[\w#!:.?+=&%#!\-\/])?(?= )/g;
I only added this "(?= )" to your regex.
Fiddle
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;
});
what would be the regular expression to check if a given string contains atleast one number and one uppercase letter?
Thanks in advance
I am doing like this
function validate_pass{
var var_password = document.getElementById("npassword").value;
else if (!(/^(?=.*\d)(?=.*[A-Z]).+$/).test(var_password))){
msg = "Password should contain atleast.";
showErrorMsgPassword(msg);
$('#npassword').val('');
$('#cpassword').val('');
return false;
}
else return true;
If the desire is to test a string to see if it has a least one digit and at least one uppercase letter in any order and with any other characters allowed too, then this will work:
var str = "abc32Qdef";
var re = /[A-Z].*\d|\d.*[A-Z]/;
var good = re.test(str);
Working demo with a bunch of test cases here: http://jsfiddle.net/jfriend00/gYEmC/
It's been a while since I've done this, and I'm fairly certain there is a more efficient way than this. You will need to use positive lookaheads, but there should be a way to remove the wildcards from within them:
This regex (/^(?=.*[A-Z])(?=.*\d).*$/) will return the entire password if it matches the criteria.
('a3sdasFf').match(/^(?=.*[A-Z])(?=.*\d).*$/);
Like below:
/(\d.*[A-Z])|([A-Z].*\d)/
To test a string matched or not:
var str = "abc32dQef";
var is_matched = /(\d.*[A-Z])|([A-Z].*\d)/.test(str);
In the following input string:
{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}
I am trying to match all instances of {$SOMETHING_HERE} that are not preceded by an unescaped backslash.
Example:
I want it to match {$SOMETHING} but not \{$SOMETHING}.
But I do want it to match \\{$SOMETHING}
Attempts:
All of my attempts so far will match what I want except for tags right next to each other like {$SOMETHING}{$SOMETHING_ELSE}
Here is what I currently have:
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}';
var results = input.match(/(?:[^\\]|^)\{\$[a-zA-Z_][a-zA-Z0-9_]*\}/g);
console.log(results);
Which outputs:
["{$foo}", "h{$blah2}", "e{$blah3}", "t{$blarg}"]
Goal
I want it to be :
["{$foo}", "{$blah2}", "{$blah3}", "{$blarg}", "{$why_not_me}"]
Question
Can anybody point me in the right direction?
The problem here is that you need a lookbehind, which JavaScript Regexs don't support
basically you need "${whatever} if it is preceded by a double slash but not a single slash" which is what the lookbehind does.
You can mimic simple cases of lookbehinds, but not sure if it will help in this example. Give it a go: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
edit
Btw, I don't think you can do this a 'stupid way' either because if you have [^\\]\{ you'll match any character that is not a backslash before the brace. You really need the lookbehind to do this cleanly.
Otherwise you can do
(\\*{\$[a-zA-Z_][a-zA-Z0-9_]*\})
Then just count the number of backslashes in the resulting tokens.
When all else fails, split, join/replace the crap out of it.
Note: the first split/join is actually the cleanup portion. That kills \{<*>}
Also, I didn't account for the stuff inside the brackets since there's code for that already.
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';
input.split(/(?:[^\\])\\\{[^\}]*\}/).join('').replace(/\}[^\{]*\{/g,'},{').split(/,/));
This seems to do what I want:
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';
var results = [];
input.replace(/(\\*)\{\$[a-z_][a-z0-9_]*\}/g, function($0,$1){
$0 = $0.replace(/^\\\\/g,'');
var result = ($0.indexOf('\\') === 0 ? false : $0);
if(result) {
results.push(result);
}
})
console.log(results);
Which gives:
["{$foo}", "{$blah2}", "{$blah3}", "{$blarg}", "{$why_not_me}"]
I'm trying to validate a field named phone_number with this rules:
the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874
or can be 7 numbers 1234567
here i have my code:
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
missing = true;
Why doesnt work :( when i put that into an online regexp checker shows good.
You should be using test instead of match and here's the proper code:
.test(/^(3\d{9}|\d{7})$/)
Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).
Don't get confused by pipe. Must end each expression
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
missing = true;
http://jsfiddle.net/alfabravoteam/e6jKs/
I had similar problem and my solution was to write it like:
if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
missing = true;
}
Try this, it's a little more strict.
.match(/^(3\d{9}|\d{7})$/)