Using JavaScript RegExp to valid email. Regex special characters not working - javascript

I've got this JavaScript function:
function emailaddresscheck() {
var emailregex = new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
var emailstring = $("#email-address").val();
if (emailregex.test(emailstring)) {
$("#email-address-check").fadeIn(100);
return true;
}
else if ($("#email-address").val().length <= 5) {
$("#email-address-check").fadeOut(100);
return false;
}
}
The if condition is firing if I have a simple string in the RegExp constructor but this more complex regex isn't working.
Where am I going wrong?
UPDATE:
This is the finished working code:
function emailaddresscheck() {
var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$");
var emailstring = $("#email-address").val();
if (emailregexp.test(emailstring) === true) {
$("#email-address-check").fadeIn(100);
return true;
}
else if (emailregexp.test(emailstring) === false) {
$("#email-address-check").fadeOut(100);
return false;
}
}

When you create a regex with the RegExp constructor you need to double escape special characters since they are inside a string.
new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
-^-
Or just use a literal regex:
/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)/

Related

Convert Javascript regex to Typescript regex

I have a regex which checks the inputText is in valid url format or not.
And working almost good:
checkUrlFormat() {
const pattern = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
But i need to make that pattern shorter so I have written a regexp in https://www.debuggex.com/#cheatsheet as
(((http|https)(://))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]
but it is in javascript format and i could not find how to use that string with the code above. When i directly copy paste it, it is giving syntax error. How can i combine them.
checkUrlFormat() {
const pattern = /^(((http|https)(:\/\/))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}

javascript regex validation function

My java-script regex validation requires the following condition.
Accept only alphabet value
Do not accept only numeric value
Do not accept only special characters
Accept combination of alphanumeric and special character value
I wrote following code to achieve it
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
if (filter.test(str)) {
return true;
}
else {
return false;
}
}
and I also tried different regex but never achieved the desired result.
Please do help me with the proper regex for my validations.
Thank You
Since, It is necessary to have alphabets in your string, simply check for that
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
var filterAlphabets = /^[ A-Za-z]*$/;
if (filter.test(str)) {
if ( filterAlphabets.test(str)){
return true;
}
else{
return false; }
}
else {
return false;
}
}
This is assuming that a combination of numbers and special characters is not allowed
If i understood the question right it should be like this
Check if it contains only numbers
Check if it contains only special symbols
function validateAlphaNumChar(str) {
var filterABC = /^[A-Za-z]*$/;
var filterNUM = /^[0-9]*$/;
var filterSPEC = /^[_##./#&+-]*$/;
if (filterNUM.test(str)) {
return false;
} else if(filterSPEC.test(str)) {
return false;
} else {
return true;
}
}
document.getElementById("demo").innerHTML = validateAlphaNumChar("A#");
<p id="demo"></p>

Javascript validate string is a character followed by numbers

I am trying to validate a string where the first character must be an 'x' and the remaining characters must be numerical. For example:
x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;
Here is my code:
function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;
// Debugging
console.log(firstLetter);
console.log(remainingCode);
if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}
I've debugged my isNumeric() function, so I'm 99.9% sure the issue isn't there, but here it is just in case:
function isNumeric(numberIn)
{
var returnValue = true;
if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
{
returnValue = false;
}
return returnValue;
}
I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking if(!(firstLetter == 'x')) I've tried == and ===and I've tried casting the remaining portion of the code with Number() , +() and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.
You can use a regular expression test:
function isValidCode(code) {
return /^[a-z]\d+$/.test(code);
}
I am making an assumption that a lower case letter is required, followed by at least one digit.
To match only only the letter 'x', use:
function isValidCode(code) {
return /^x\d+$/.test(code);
}
You can use RegExp /^x(?=\d+$)/ to match x at beginning of input followed by digits followed by end of input
var arr = ["x1234"
, "k1234"
, "x12k4"
, "1x123"];
var re = /^x(?=\d+$)/;
arr.forEach(function(str) {
console.log(`${str}: ${re.test(str)}`)
})

Regex Javascript in order to know if a pattern is containing in a String

I have a JavaScript String, for example :
var test1 = "aaaaaa#bbbbb.temp" ; // Function must return true in this case
var test2 = "ccccc#ddddd.fr " ; // Function must return false in this case
I would like to build a function which return true if the String contains # character, following by any character "bbbbbb" following by ".temp" extension.
How can I do this ?
You can use regex#test
var found = /#.*?\.temp\b/.test(str);
If you want to make it # character, following by "bbbbbb" following by ".temp" extension then use:
var found = /#bbbbbb\.temp\b/.test(str);
Regular expression solution:
function validate(argument) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if((argument.lastIndexOf('.temp', argument.length-5)>=argument.length-5) && re.test(argument)) {
return true;
} else {
return false;
}
}
JsFiddle test: http://jsfiddle.net/2EXxx/

Convert string to RegExp

How can I check a JavaScript string is in a RegExp format, then convert it to RegExp?
I found a way with RegExp, but the rule is too complex to make it right.
function str2Regex(str){
var rule = /\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/([gim]*)/;
var match = str.match(rule);
return match ? new RegExp(match[1],match[3]) : str;
}
Now I'm using /\/(.*)\/(?=[igm]*)([igm]*)/ which works.
The simplest way, and probably the most correct, is to use try/catch :
try {
r = new RegExp(str);
} catch(error) {
// no good
}
You get a SyntaxError when the string doesn't match a well formed regular expression.
If you want to test a string whose value is like a compiled regular expression (for example "/\b=\b/g", you can use such a function :
function checkCompiledRegex(str) {
if (str[0]!='/') return false;
var i = str.lastIndexOf('/');
if (i<=0) return false;
try {
new RegExp(str.slice(1, i), str.slice(i+1));
} catch(error) {
return false;
}
return true;
}

Categories