Javascript Special Character Password Validation without JQuery - javascript

I would like to write a simple if statement to test for special characters. Something like this:
var passwordSpecial = **WHATDOIPUTHERE???**.test(password)
if(passwordSpecial == true){
var pass="OK"
}
else{
var pass="NO"
}

const pattern = new RegExp(/^[^#]+$/);
const password1 = pattern.test("hey")
const password2 = pattern.test("#hey")
//returns true, false
console.log(password1, password2)
anything you put inside the brackets after the "^" won't be allowed in the string, in this case "#"
Edit: see this code pen
https://codepen.io/PavlosKaralis/pen/vYLeYqp?editors=1011
And if you want to specifically only allow numbers and letters
const pattern = new RegExp(/^[a-zA-Z0-9]*$/);
It depends on your definition of what a special character is.

Related

Regular Expression Pattern matching issue

Not a lot of experience in RegEx stuff.
I have the following in java script which works perfectly fine.
The following pattern is used allow only alpha numeric
var valid = /^[A-Za-z0-9]+$/.test("a"); // returns true
var valid = /^[A-Za-z0-9]+$/.test("#"); // returns false
I am using the pattern part "^[A-Za-z0-9]" in some other places of the code and was asked to use the part "^[A-Za-z0-9]" in a variable and use it so that it is not repetitive. The following is a modification to the above:
var regExPart= "^[A-Za-z0-9]";
var regExString = ("/" + regExPart+ "+$/".replace(/\"/g, "")); // replacing the quotes
var regExp = new RegExp(regExString); // results in /^[A-Za-z0-9]+$/
var valid = regExp.test(charValue); // charValue could be any keyvalue "a" or "#"
//the above returns false for "a"
//the above returns false for "#"
I am writing this in a keypress event to allow only alpha numeric
keypressValidation: function (e) {
var charCode = (e.which) ? e.which: event.keyCode;
var charValue = String.fromCharCode(charCode);
var valid = return /^[A-Za-z0-9]+$/.test(charValue);
if (!valid)
{
//prevent default (don't allow/ enter the value)
}
Not sure why. What am I missing in this. Need to return true for "a" and false for "#" for both the approaches. Any help/ suggestion would be of great help. Thank in advance.
For the RegExp class constructor, you do not need to specify forward slashes /.
var regExPart= "^[A-Za-z0-9]";
var regExp = new RegExp(regExPart + "+$"); // results in /^[A-Za-z0-9]+$/
console.log('a', regExp.test('a'))
console.log('#', regExp.test('#'))
It is not a must to contain '/'s in regexp
new RegExp("^[0-9a-zA-Z]$").test('a')
return true
new RegExp("^[0-9a-zA-Z]$").test('#')
return false
So just do
var rex="^[0-9a-zA-Z]$"
And you can use it anywhere. Tested in Chrome console.
I've made an example using your regex of what it should do, i think the way you were building your regex was not helping. You don't need to create a string and then create a new regex object , you can use /regex part/.
Anyways here is a working example.
function keypress(e) {
// Get the current typed key
var keynum = e.key;
// this regex only allow character between a and z and 0 and 9
var regex = /^[a-zA-Z0-9]+$/;
// we check if the current key matches our regex
if(!keynum.match(regex) ) {
// it doesn't ? well we stop the event from happening
e.preventDefault();
}
}
<input type="text" onkeypress="keypress(event)">

Javascript regex doesn't give error message when it should

I try to input the following value "f+11111111111", and my code doesn't display error message. I tried to remove regex2 condition, and then it worked. But how come? It's an AND condition, why does it act like it's an OR operator?
function validatePhone()
{
var phone = document.getElementById("phone").value;
var regex1 =/^[\+\d][\s(\-\d][\s()\-\d]{8,}/g;
var regex2 = /\D*(\d\D*){11}/g;
if (!phone.match(regex1) && !phone.match(regex2)) {
producePrompt("Error", "comment_phone_prompt");
return false;
}
}
function producePrompt(message, promptLocation)
{
document.getElementById(promptLocation).innerHTML = message;
}
Your second regular expression /\D*(\d\D*){11}/g matches the given string f+11111111111 and therefore the whole condition evaluates to false. You can visualise your regular expressions using regexper.com.
I'm not sure what you're trying to do but mind that even this string is matched by the second regex: 'f+1dsadsadasda123131231dsdadai-094i-)#)#(#)_(#_!' Is this what you want?
Second regex matches everything. Single regex is enough.
function validatePhone() {
var phone = document.getElementById("phone").value;
var regex1 = /^(\+\d)?(\(|-)?\d{3}(\)|-)?\d{3}-?\d{4}$/;
//match +1-800-123-45678, (555)123-4567, and so on
if (!regex1.test(phone)){
producePrompt("Error", "comment_phone_prompt");
return false;
}
return true;//both sides should return
}

Match a string(input text from user) with regular expression

I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry.
Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :
[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}
The code is like below:
var str = "*aaa*";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa***";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa*$$$$";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.
Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$
Use anchors ^$ to disable partial matching.See demo.
https://regex101.com/r/tS1hW2/17
The string *aaa*$$$ contains a segment of *aaa*, so it will yield true; to match against the whole string you need to add anchors on both sides. The $ and ^ anchors assert the start and end of the subject respectively.
Also, you can simply the expression greatly by using a character class trick. The \w is comprised of [0-9a-zA-Z_], and we only don't want the underscore, so we can use a negative character class with the opposite of \w (which is \W) and an underscore; I agree, it takes some mental power ;-)
var str = "*aaa*$";
var patt = /^\*[^\W_]{3,}\*$/;
var res = patt.test(str);
alert(res); // false
Alternatively, you can merge all your character classes together into one like so:
[A-Za-z0-9]

Javascript RegExp.test not working

I'm trying to write a regular expression for a strong password.
/* Regular expression explained
o Must contain at least one number: (?=.*\d)
o Must contain at least one letter: (?=.*[a-zA-Z])
o Must contain at least one symbol: (?=.*[!##$*_=|?{}\[\]~\-,.])
o No whitespace: (?=\S+$)
o Length 8 - 25 characters long: .{8,25}
*/
pass = document.getElementById('password').value;
var PwdRegExpStr = "^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"
var PwdRegExp = new RegExp(PwdRegExpStr);
var PwdRegExpStr2 = "^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$?]).*$"
var PwdRegExp2 = new RegExp(PwdRegExpStr2);
var patt = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$/
var patt2 = /^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/
alert("Pass:"+pass+" = "+PwdRegExp.test(pass)+" = "+PwdRegExp2.test(pass)+" = "+patt.test(pass)+" = "+patt2.test(pass));
I'm seeing the following results when i enter "qwer1234$":
Pass:qwer1234$ = false = false = true = true
Can you help me understand why they're not all evaluating true?
Thanks
Your main problem is bad escaping. When you specify the regex in the form of a string literal, you have to escape the backslashes. So this:
"^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"
...should be:
"^(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!##$*_=|?{}\\[\\]~\\-,.])(?=\\S+$).{8,25}$"
On a side note, I don't see any need to write (?=\S+$).{8,25}$ when \S{8,25}$ will do. And in your other version, the extra .* after the ^ makes no sense. It still works, but you're making the regex engine do a lot more work than it should.

Node.JS - How would I do this regex?

Well I have this:
var regex = /convertID\s(\d+)/
var match = regex.exec(message);
if(match != null)
{
//do stuff here
}
That works fine and it recognizes if someone writes "convertID NumbersHere".
However I want to have another one under it as well checking if there's a specific link, for example:
var regex = /convertID\shttp://anysitehere dot com/id/[A-Z]
var match = regex.exec(message);
if(match != null)
{
//do stuff here
}
So how would I make it check for an specific site with any letters after /id/?
You can use this:
var regex = /convertID\shttp:\/\/thesite.com\/id\/[A-Za-z]+/;
slashes must be escaped since the slash is used to delimit the pattern. You can avoid this creating explicitly an instance of RegExp class:
var regex = new RegExp("convertID\\shttp://thesite.com/id/[A-Za-z]+");

Categories

Resources