I am using a regex to validate an email address in JavaScript.
The regex is pretty simple. It checks three things: 1)'#' , 2)'.' ('dot' as in something#gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)
Here is the code:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/#/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
My question is:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
returns false even when there are no dots in string.
For example:
("thisIsMyEmail".match(/./ig))==null //returns false
Why does it return false when it should be true?
/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."
For an actual dot, escape it with a backslash: /\./g.
First off, you don't need to check if the string is null. Simply use this:
var email = "Godisgood#gmail.com";
if (email.match(/^\S+\#\S+\.\S+$/i)){
alert("Email address passed validation.");
}
you have to escape the .
The unescaped period means matches any character.
Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.
In your snippet the correct answer is
(e.match(/\./g)==null);
This should result to what you're expecting
Try this
(e.match(/\./g)==null);
. matches any character so needs escaping /\./g
I know you have already got the answer.
But I just want to give an advice.
My advice is - don't use the javascript code to validate any email address; because as per your code, #domain., #domain.com these all are also valid email, but everybody knows these are not a valid email address.
So use the below code:
let email = $(this).val();
var positionOfAt = email.indexOf("#");
var positionOfDot = email.lastIndexOf(".");
if(email.search("#") == -1 || //if '#' is not present
email.search(" ") >= 1 || //if blank space is present
email.search(".") == -1 || //if "." is not present
positionOfAt < 1 || //if there is no character before "#", at least one character should be present before "#"
positionOfDot - positionOfAt <= 2 || //between '#' and '.', if there is not at least two character
email.length - positionOfDot <= 2) //if after '.' there is not at least two character)
{
console.log("Invalid email id")
}
else
{
console.log("Valid email id")
}
Related
I'm attempting one of the beginner coderByte challenges, Simple Symbols. Challenge summary below.
"Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter."
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
The first regular expression I'm testing, /^\w/gi, comes back undefined, and I can't figure out why?
https://regex101.com/ is a great tool I've used before, and my expression does identify f as the first character in the string, but when I test it in codepen, it comes back undefined in the console.
Code
See regex in use here
^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$
Alternatively, using the opposite logic (catching invalid strings instead of valid ones), you can use (?:^|[^+])[a-z]|[a-z](?:[^+]|$)
Usage
Please note the valid/invalid strings below have been created according to the OP's explanation of valid and invalid strings: That each letter must be surrounded by a + symbol. and that the plus sign + may be shared between characters such that +a+a+ is valid (specified in comments below the question).
var a = [
// valid
"++d+===+c++==+a++",
"+a+a+a+",
"+a++a+",
"+a+",
// invalid
"++d+===+c++==a",
"+=d+",
"+dd+",
"+d=+",
"+d+d",
"d+d+"
];
var r = /^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$/mi;
a.forEach(function(s){
console.log(r.test(s));
});
Explanation
^ Assert position at the start of the line
[+=\d]* Match any number of characters in the set (+, =, or digit)
\+ Match a literal plus sign +
(?:[a-z]\+[+=\d]*)+ Match one or more of the following
[a-z] Match a lowercase ASCII letter
\+ Match a literal plus sign +
[+=\d]* Match any number of characters in the set (+, =, or digit)
$ Assert position at the end of the line
It's returning undefined because your expression does not meet any of the criteria. Since you have no else {} defined, than nothing gets returned. Thus you get undefined. Try this:
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
} else {
return "catch all here";
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
You can use a single regex and the string.test() method (which returns just true/false).
Below are 2 different ways (regex) to do it .
First requires a separate + between word chars. Example +a++b+ (true)
^
(?: [+=]* \+ \w \+ [+=]* )+
$
Second can take a common + between word chars. Example +a+b+ (true)
^
(?:
[+=]* \+ \w
(?= \+ )
)+
[+=]*
$
var patt1 = new RegExp("^(?:[+=]*\\+\\w\\+[+=]*)+$");
function SimpleSymbols_1(str){
return patt1.test(str);
}
var patt2 = new RegExp("^(?:[+=]*\\+\\w(?=\\+))+[+=]*$");
function SimpleSymbols_2(str){
return patt2.test(str);
}
console.log(SimpleSymbols_1('+d+=3=+s+'));
console.log(SimpleSymbols_1('f++d+'));
console.log(SimpleSymbols_1('+a+b+c+'));
console.log(SimpleSymbols_2('+a+b+c+'));
console.log(SimpleSymbols_2('+a+=+c+'));
console.log(SimpleSymbols_2('+a++c+'));
Thank you all for throwing some support/comments my way. Again, I am new to JavaScript and Regular Expressions are fairly foreign to me, though I am gaining some traction in understanding them. Here is the updated solution I posted. It's quite convoluted and perhaps a more inelegant and non-simple way to come to the right answer, but it worked.
function SimpleSymbols(str){
var RegExp = /\+[a-z]\+/gi;
var regexp1 = /^[a-z]/gi;
var regexp2 = /[a-z]$/g;
var regexp3 = /[a-z]\=/gi;
var regexp4 = /\=[a-z]/gi;
if(regexp1.test(str) === true){
return false
} else if(regexp2.test(str) === true){
return false
} else if(regexp3.test(str) === true){
return false
} else if(regexp4.test(str) === true){
return false
} else {
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
console.log(SimpleSymbols('+d===+a+'));
console.log(SimpleSymbols('+a='));
console.log(SimpleSymbols('2+a+a+'));
console.log(SimpleSymbols('==a+'));
I was sure there had to be a way to use only one regular expression, but again, I'm still very much a novice.
Thanks again everyone.
I have a form field in my PDF that requires five capitalized letters as input, or nothing at all. Everything else should result in an error. I got the first part working, but I'm making some kind of mistake in checking for an empty field. Here's my Javascript:
event.rc = true;
var myRegExp = /^[A-Z]{5}$/;
var myTextInput = event.value;
if ( !myRegExp.test(myTextInput) || myTextInput != "" )
{
app.alert("Your order number prefix must be formatted as five characters, all caps.");
event.rc = false;
}
Change the regex to
var myRegExp = /^([A-Z]{5})?$/;
to allow an empty string match and remove || myTextInput != "" condition that becomes irrelevant.
A (...)? group is an optional one because ? matches 1 or 0 occurrences of the quantified subpattern.
Trying to validate my form and set up a variable for invalid characters, but I'm having trouble getting them recognized because they're just a bunch of symbols? -
function validation(){
var Name =
document.getElementById("name").value;
var Email = document.getElementByID("email").value;
var invalidSymbol = /[\~\`\!\#\$\%\^\&\*\(\)\-\+\{\}\:\\\;\"\'\<\>\?\,\]/;
if Name == ""{
alert("Please enter your name");
document.getElementById("Name").focus();
return false;
}else if (Email == "" | | Email.indexOf("#")<1 || Email.lastIndexOf("#")+2 || Email.lastIndexOf(".")+2>=Email.indexOf("#").length || Email.match(invalidSymbol)){
alert ("Please enter a valid e-mail address");
document.getElementById("email").focus();
return false;
}else{
return true;
}
}
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist
- replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say
global and case-insensitive (the latter is a bit redundant but I
wanted to mention it) and the safelist in this example is digits, word
characters, underscores (\w) and whitespace (\s).
As stated here:
javascript regexp remove all special characters
by
annakata
I am creating a small very simple game.
I want to know how to accept any input value in the following code...
if(answer === "My name is" + * + "and I am a Leo" ) {
alert("Correct!")
}
To my understanding the asterisks would accept any value input by the user.
Besides that, script breaks after i write the above.
Forgot to add the JSFIddle
Try this:
if (answer.substring(0, 10) == "My name is" && answer.slice(-14) == "and I am a Leo") {
alert("Correct!");
}
substring(0, 10) -> gets the first 10 characters
slice(-14) -> gets the last 14 characters
Here's a regex approach too:
var matches = answer.match(/^My name is (.*) and I am a Leo$/);
if (matches != null) {
alert("Correct!"); //use matches[1] to get the name
}
I assume you have already prompted the user for a value to the answer variable.
You probobly want to use a regeular expression:
if (answer.search(/^My name is.*and I am a Leo$/) === 0) {
alert("Correct!");
}
Look at this cheatsheet to see what the difference characters mean. The search method returns the position of the match in the string, or -1 at failure. In this case, since ^ matches the start of the string, it will always return 0 on success.
$ matches the end of the string and .* means match any character except newline 0 or more times (that is any amount of times).
I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)
Allowed:
John
john
Not Allowed
john kennedy.
John kennedy.
john123.
123john.
I tried this but its not working.
if( !validateName($fname))
{
alert("name invalid");
}
function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
return false;
} else {
return true;
}
}
EDIT:
I tried
var nameReg = /^[A-Za-z]*/;
but it still doesn't show the alert box when I enter john123 or 123john.
nameReg needs to be /^[a-z]+$/i (or some varient). The ^ matches the start of the string and $ matches the end. This is "one or more a-z characters from the start to the end of the string, case-insensitive." You can change + to *, but then the string could be empty.
http://jsfiddle.net/ExplosionPIlls/pwYV3/1/
Use a character class:
var nameReg = /^[A-Za-z]*/;
Without the containing [] (making it a character class), you're specifying a literal A-Za-z.
UPDATE:
Add a $ to the end of the Regex.
var nameReg = /^[A-Za-z]*$/;
Otherwise, john123 returns valid as the Regex is matching john and can ignore the 123 portion of the string.
Working demo: http://jsfiddle.net/GNVck/