must at least have number and characters regex - javascript

I still don't understand how to use regex and there is regex like this :
/^[a-zA-Z0-9\s]+$/
and i use it in javascript
$('#oldPass, #newPass, #confpass').keydown(function (e) {
var inputValue = e.key;
if(inputValue.match(/^[a-zA-Z0-9\s]+$/)){
return;
}else{
e.preventDefault();
}
});
it works, i can't type anything beside alphanumeric, but how can i make that the new password must contain combination number and characters?

Minimum of 8 letters with atleast one letter and number.
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}
check this link for verification
https://regex101.com/r/DcxNSc/1

Related

how can I fix password validation conditions with correct regex?

I am trying to fix my logical conditions that aren't working as intended.
For instance, the "2 digits in a password" condition fails on 1test2 even though it has 2 digits in it.
My rules are:
password must have at least 2 digits
password must have at least 6 letters
password must have at least 1 special character
password must be at least 8 characters long
https://codepen.io/skybulk/pen/OJNMPYO
function checkPassword(pwd){
const special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
if(/[0-9]{2,}/.test(pwd)){ // at least 2 digits
return true;
}
if(/[a-zA-Z]{6,}/.test(pwd)){ // at least 6 letters
return true;
}
if(new RegExp(special_characters).test(pwd)){ // at leas 1 special character
return true;
}
if(pwd.length < 8){
return true;
}
}
I have not made any changes to your Regexp - only to the logic surrounding it. You might want to start with a variable valid and if any of these conditions are not met you can set valid = false. At the end of your function you want to return valid which will be a boolean of true or false depending on whether the password passed all tests.
function checkPassword(pwd){
let valid = true;
const special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
if (!/[0-9]{2,}/.test(pwd)){ // at least 2 digits
valid = false;
}
if (!/[a-zA-Z]{6,}/.test(pwd)){ // at least 6 letters
valid = false;
}
if (!new RegExp(special_characters).test(pwd)){ // at least 1 special character
valid = false;
}
if (!pwd.length < 8){
valid = false;
}
return valid;
}
Side note: Complex password validation can be restrictive to the user. It is far more secure to encourage a user to have a longer password (or pass phrase) than a shorter password with a few special characters.
You may use
const regex = /^(?=.{8})(?=(?:\D*\d){2})(?=(?:[^a-zA-Z]*[a-zA-Z]){6})(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]])/
See the regex demo (the pattern is a bit modified to avoid matching line breaks as the demo is performed against a single multiline string).
Details
^ - start of string
(?=(?:\D*\d){2}) - password must have at least 2 digits
(?=(?:[^a-zA-Z]*[a-zA-Z]){6}) - password must have at least 6 letters
(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]]) - password must have at least 1 special character
(?=.{8}) - password must be at least 8 characters long.
You may write the regex with comments inside the code, too:
const regex = new RegExp("^" + // start of string
"(?=.{8})" + // must be at least 8 characters long
String.raw`(?=(?:\D*\d){2})` + // must have at least 2 digits
"(?=(?:[^a-zA-Z]*[a-zA-Z]){6})" + // must have at least 6 letters
String.raw`(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]])` // must have at least 6 letters
);
console.log(regex);
Try with this. It seems easier to read and maintain:
function checkPassword(pwd){
const special_characters = /[%~!##$\^&*()_+{}":;,'\[\]]/;
return pwd.replace(/[^0-9]/g, '').length >= 2
&& pwd.replace(/[^a-zA-Z]/g, '').length >= 6
&& special_characters.test(pwd)
&& pwd.length >= 8
}
console.log(checkPassword('FF%lkf%jd%fk12'));
The idea is for every condition, remove all not-to-be-tested characters. Then you have the length of the characters that you are testing.
Bear in mind that in javascript, you can create a Regex object with the syntax:
some_variable = /foobar/;
You can create it via new Regex, however, in that case you are passing a string to the constructor. So if the regex was supposed to have a backslash, you should scape it too. Also, as regular strings, quotes should be scaped (one backslash).
This two are equivalent:
special_characters = /[%~!##$\^&*()_+{}":;,'\[\]]/;
special_characters = new Regex("/[%~!##$\\^&*()_+{}\":;,'\\[\\]]/");
Note that only ], ^, - must be scaped ([ is recommended and a must on other programming languages)
Also, when I read \! I was not sure if you tried to scape ! (which is unnecessary) or you tried to add backslash to the special character list (I opted for the first)

Form validation to check repetition in string

I want to check the entered string in text-box for repetition. i.e. I want to accept only those String which have no repetition and can have all alphabets (CAPS ON & off) + special characters and all digits?
I tried this regexp for checking repetition
var pattern = /(\d).*\1/;
and as everything is allowed when it comes to range so i did not make any check for the same but it is not working.
Can anyone help me out with something that can make my Spin. :-)
Example - vCc##^k->Valid VbhUiu->Valid mnkOOp->Invalid fgty^^m->Invalid
var pattern = /(.).*\1/;
if (pattern.test(str)) {
alert("No repetition allowed");
} else {
alert("Looks good!");
}
DEMO

Regex to validate a password [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}
Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.
You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])
Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.
What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.

What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules...
it will include 10 digits
if there is a leading 1 or +1 it should be ignored
valid characters allowed in the field are... 0-9,(), and -
I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^adfafsd. I believe the error is in my code not the regex. For example, are there supposed to be quotes around the expression?
Here is the code that is supposed to be validating the phone field...
$('#phone').bind('blur', function() {
var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
if(pattern.test($('#phone').val())){
$("#phone").addClass("error");
return false;
}else{
$("#phone").removeClass("error");
return true;
}
return true;
})
When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. Try this instead:
var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;
if(regex.test($('#phone').val()){ ... }
if there is a leading 1 or +1 it should be ignored
it will include 10 digits
valid characters allowed in the field are... 0-9,(), and -
That could be matched with an expression like:
/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/

Form validation of numeric characters in JavaScript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}

Categories

Resources