Regular Expression to validate email: illegal character - javascript

Doing form validation using Jquery without plugins, they're easy enough to use. Trying to teach myself regular expressions and at a wall.
var email = $('#email').val();
// Validate email address
// Regular expression to match email address:
var emailReg = \S+#\S+;
if(email.match(emailReg)) {
// Pass
}
else {
// Fail
$('#email').css("background","yellow");
var counter2 = setTimeout("$('#email').css('background','white')", 3000);
return false;
}
I know it's the worlds simplest regular expression, just trying to get functionality and I'll get more sophisticated later.
Keep getting SyntaxError: illegal character \S (here) +#S+
Don't understand why. Have searched this site and tried dozens always with console errors.

Add / around it.
var emailReg = /\S+#\S+/;
^ ^

You need to place your regex in forwardslashes like so:
var emailReg = /\S+#\S+/;
This way it knows it's a regex object, instead of just random operators put together
You could also do:
var emailReg = new RegExp("\S+#\S+");
This method is useful if you aren't just writing a static regex (eg. getting the regex from user input)

Regular expressions are enclosed in forward slashes in js. Try
var emailReg = /\S+#\S+/;

Related

Regular expression failed in URL address test

I try to build an Regular expression to check valid URL address. for now I tested different address and all was good , but those next (valid) address's failed:
url = "http://example.com/tr/vvf/index.php/docs/po/trf"
//url = "http://example-a.mydomain.com/test/ny" also not working
var pattern = new RegExp("(https|ftp|http)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?");
pattern.test(url)
I think because of the index.php/doc... Any ideas how to fix it
Just use regex literal instead of RegExp object:
var pattern = /(https|ftp|http):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
RegExp works with a string, that requires you to do double escaping so \w becomes \\w in it.
See it working here

Regex expression to match the First url after a space followed

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

javascript regex does not work properly with postal code

'^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$'
the above regular expression accepts inputs like T3K2H3 or T3K-2H3 from .net form but when i run the validation through the javascript; it does not work.
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$');
var postalCode = 't3k2h3';
var matchesPostalCode = rxPostalCode.exec(postalCode);
if (matchesPostalCode == null || postalCode != matchesPostalCode[0]) {
$scope.AccountInfoForm.PostalCode.$setValidity("pattern", false);
$scope.showLoading = false;
return false;
}
I believe that in javascript, you have to do // instead of ''
as follows:
/^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\d{1}$/
You might want to check the following link:
Validate email address in JavaScript?
You have two syntaxes to define a regexp object:
var rxPostalCode = /^[abceghj-np-tvxy]\d[abceghj-np-tv-z][ -]?\d[abceghj-np-tv-z]\d$/i;
or
var rxPostalCode = new RegExp('^[abceghj-np-tvxy]\\d[abceghj-np-tv-z][ -]?\\d[abceghj-np-tv-z]\\d$', 'i');
Note that with the second syntax you need to use double backslashes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
"Do not forget to escape \ itself while using the RegExp("pattern") notation because \ is also an escape character in strings."
var rxPostalCode = new RegExp('^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]{1}\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}[ -]*\\d{1}[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]{1}\\d{1}$');
That should work, I tested it in Chrome's console.
Try the following pattern:
^[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz][ -]*\d
[AaBbCcEeFfGgHhJjKkLlMmNnPpRrSsTtVvWwXxYyZz]\d
Remove the $ at the end and see if that solves your problem.
I also simplified things a bit, the \d{1} is the same as \d
I would also change the [ -]* to [ -]? unless you want to allow multiple spaces or dashes
I suspect what is happening is that the $ expect the end of the line or string, and JavaScript may not store the VAR properly. See if remove the $ solves it, or possibly keeping the $ and trim() the string.

Invalid regular expression in Javascript on Lookarounds

I'm having a problem with the regex that work in Expresso but not in the javascript code. I know that there are also two other question with the same topic, but can't figure out how to implement an alternative to my regex so that it will work also in javascript.
So my expression is:
((?<=\bvar)\s\w*\s?)=\s?function(\s*\([^)]*\))
Used in javascript like that:
var functionsReg = /((?<=\bvar)\s\w*\s?)=\s?function(\s*\([^)]*\))/gm;
var match = functionsReg.exec(func);
and I'm expecting to be able to get for the values for each regex group.
like:
var name = match[0];
var params = match[1];
I found out that the problem is from the (?<=\bvar)
But I can not find the alternative for this syntax because in the end I want to be able to access the text like in the below image.
Just match the var in a non-capture group:
/(?:var)\s+(\w+)\s*=\s*function(\s*\([^)]*\))/g

How do I use match() for a white list of characters?

I used preg_match for my server-side validation but I want to have a client side too.
For my PHP I allow those characters:
'/^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/'
How would I make a white list of characters with match() in JavaScript?
EDIT:
I tried this but it didn't work for some reason:
My debugger says, right before the if statement:
218SyntaxError: Invalid regular expression: range out of order in character class
$('#title').blur(function(){
input = $('#title').val();
var invalidChars = /^[^a-z][^a-z\d .:-,!?]+$/i;
if (!invalidChars.test(input)){
alert('true');
}
else {
alert('false');
}
});
all of the above answers are correct, though just a side-note: instead of writing [A-Za-z], a simple /[a-z]/i will suffice. The i is a case-insensitive flag...
var validChars = /^[a-z][a-z\d .:\-,!?]+$/i;
if (validChars.test(myText)){ ... }
Using regex.test(str) is slightly more performant than str.match(regex) if all you want is to know if a match exists or not.
Alternatively, you can early out if you see any invalid character:
var invalidChars = /^[^a-z][^a-z\d .:\-,!?]+$/i;
if (!invalidChars.test(myStr)){
// we passed
}
This allows the regex test to stop the moment it sees a disallowed character.
Try the following
var text = ...;
if (text.match(/^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/)) {
...
}
Actually it's the opposite:
var regexp = /^[A-Za-z][a-zA-Z0-9 .:-,!?]+$/;
if (regexp.test(text)) {
}

Categories

Resources