Javascript password validation using regex - javascript

I have a problem with my password validation using regex on javascript. the criteria are :
have at least one or more letter(it can be upper case or lower case)
have at least one or more number
character length minimal 3 and maximal 30
I hope anyone can help me to solve this problem :)
var ch_pass = /^([0-9]+).([a-zA-Z]+).({3,30})$/;

You can use lookahead like this:
var ch_pass = /^(?=.*?[0-9])(?=.*?[a-zA-Z]).{3,30}$/;

I wouldn't recommend trying to do this whole check in a single regular expression because it just over complicates it. Do each condition individually.
Has at least one letter:
var has_letters = (/[a-zA-Z]/).test(password);
Has at least one number:
var has_numbers = (/[0-9]/).test(password);
Has between 3 and 30 characters (inclusive):
var has_length = 3 <= password.length && password.length <= 30;
This can all be wrapped up into a function:
function is_password_valid(password) {
var has_letters = (/[a-zA-Z]/).test(password);
var has_numbers = (/[0-9]/).test(password);
var has_length = 3 <= password.length && password.length <= 30;
return has_letters && has_numbers && has_length;
}
Or if you prefer something more dense:
function is_password_valid(password) {
return ((/[a-zA-Z]/).test(password)
&& (/[0-9]/).test(password)
&& password.length >= 3
&& password.length <= 30);
}

Related

Javascript password validation at least 2 number digits [duplicate]

This question already has answers here:
Regular Expression for password validation
(6 answers)
Closed 7 years ago.
I am trying to write a javascript validation for a password with the following criteria:
Password Must:
Have exactly 8 characters
Contain letters and numbers
Contain at least two numbers
EG:
"helloo15", "1helloo5" and "h1111111" are valid, "helloo1500", "27272727"and "helloos5" are invalid.
This is what I currently have:
//Password
var pw = document.myForm.password1.value;
var Vpw = /^[a-zA-Z0-9]{8}$/;
if (!Vpw.test(pw)) {
alert("Password must be 8 digits long. It must include a maximum of two numbers.");
return false;
} else {
/* alert("Valid CCV!"); */
}
But I can't figure out how to limit it to a minimum of 2 numbers anywhere in the string. Thanks!
try this one
var pass = "some44Passddword"; //document.myForm.password1.value;
var patt = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");
if ( !patt.test(pass) )
{
alert("Password must be 8 digits long. It must include a maximum of two numbers.");
//return false;
}
else
{
alert("Valid!");
}
you can check this here: https://jsfiddle.net/esj9go59/
UPDATE
for also avoiding non-word characters like "$%#^&" you should use
^(?!(.*[^a-zA-Z0-9]){1,})(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$
regular expression.
Please notice that for some reason javascript test function does not respect \W as non-word characters and it is better to use [^a-zA-Z0-9] instead of this as stated in comment below
I know everyone has come through here and told you to use regular expressions (partly because you started with that). Please don't. There are times in which regular expressions are the better choice. That is rare though, they are way overused, and this is not one of those times. The following code is way more readable than the regex mess in the accepted answer.
This code also allows you to test each condition individually and give customized errors to the user.
function isValidPassword(str)
{
return str.length == 8 &&
digitCount(str) >= 2 &&
hasLetters(str) &&
hasOnlyLettersAndDigits(str);
}
function isAsciiCodeLetter(asciiCode)
{
return (65 <= asciiCode && asciiCode <= 90) ||
(97 <= asciiCode && asciiCode <= 122);
}
function isAsciiCodeDigit(asciiCode)
{
return 48 <= asciiCode && asciiCode <= 57;
}
function hasLetters(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeLetter(str.charCodeAt(i)))
return true;
}
return false;
}
function hasOnlyLettersAndDigits(str)
{
for (var i = 0, len = str.length; i < len; i++)
{
var asciiCode = str.charCodeAt(i);
if (!isAsciiCodeLetter(str.charCodeAt(i)) &&
!isAsciiCodeDigit(str.charCodeAt(i)))
{
return false;
}
}
return true;
}
function digitCount(str)
{
var count = 0;
for (var i = 0, len = str.length; i < len; i++)
{
if (isAsciiCodeDigit(str.charCodeAt(i)))
{
count++;
}
}
return count;
}
Don't use regex, but if you're dead set on using regex, match on [0-9].*[0-9] for 2 digits, [a-zA-Z] for a character, and ^[0-9a-zA-Z]{8}$ for the length and characters/digits only requirement. That's at least sort of readable:
function isValidPassword(str)
{
var atLeastTwoDigits = new RegExp("[0-9].*[0-9]");
var atLeastOneCharacter = new RegExp("[a-zA-Z]");
var onlyEightCharactersAndDigits = new RegExp("^[0-9a-zA-Z]{8}$");
return atLeastTwoDigits.test(str) &&
atLeastOneCharacter.test(str) &&
onlyEightCharactersAndDigits.test(str);
}
Test cases:
alert(isValidPassword("asdfasdf")); //false
alert(isValidPassword("asdfasd4")); //false
alert(isValidPassword("7sdfasd4")); //true
alert(isValidPassword("asdfas`f")); //false
alert(isValidPassword("asd3a4df-")); //false
alert(isValidPassword("asd3a4f-")); //false
alert(isValidPassword("asd3a4df")); //true
alert(isValidPassword("12345678")); //false
alert(isValidPassword("1helloo5")); //true
alert(isValidPassword("helloos5")); //false
alert(isValidPassword("45345345")); //false
alert(isValidPassword("123`567d")); //false
You can use another regex for that:
//This will yield FALSE (as you expect)
var pw = "1jkj3kjlkj3"
alert(pw.replace(/[^0-9]/g,"").length >= 2)
You can create a function or add that into your if.

Javascript validation - Min/Max number of characters AND must contain number

I have the following problem:
I need to validate an input (password field) with Javascript / jQuery
The rules are:
it must be 8 to 32 characters
it must contain letters AND at least one number
So my logic is the following but I can't seem to be able to implement it
be 8 to 32
if it's NOT 8 to 32 characters and doesn't have numbers
{
jQuery('#passwordfield').addClass('error');
}
I tried the following (just with 0 as number, for test purposes)
if(((jQuery('#passwordfield').val().length <= 7) || (jQuery('#passwordfield').val().length >= 33)) && ((jQuery('#passwordfield').val().indexOf("0") == -1)))
{
jQuery('#passwordfield').addClass('error');
}
The problem with the above code is that it returns true if you type enough characters (8 to 32) and NOT contain a number since the first part of the && is true
Try this :
var p = jQuery('#passwordfield').val();
if(p.length <=7 || p.length >= 33 || !p.match(/\d/) || !p.match(/[a-z]/i))
$('.whatever').addClass('error');
You can use regular expression:-
var val = jQuery('#passwordfield').val();
if(val.length <=7 || val.length >= 33 || !/[0-9]/.test(val) || !/[a-zA-Z]/.test(val))
{
// show error
}
String must contain 0..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/\d/) == -1) {
jQuery('#passwordfield').addClass('error');
}
String must contain 1..* letters and 1..* numbers (with a total length of 8..32):
if (str.search(/^[a-zA-Z0-9]{8,32}$/) == -1 || str.search(/[a-zA-Z]\d|\d[a-zA-Z]/) == -1) {
jQuery('#passwordfield').addClass('error');
}

How Can I Use a Regular Expression to Test for a Specific Decimal?

I have a field where the user needs to input the width of their window. It needs to be between 16.75 and 48 and only in .25 increments (so it has to end in .00, .25, .50, .75). I have tried the following to test my regular expressions on the number 31.25 but the all return false. I've trolled the internet but can't find much help for a regex novice like me. Can someone please help me with the regex for this?
Here is the field:
<input type="text" id="windowWidth" onchange="basePrice()">
Here is the JS:
function basePrice()
{
var windowWidth = document.getElementById("windowWidth").value;
var windowHeight = document.getElementById("windowHeight").value;
if (windowWidth != "" && windowWidth > 16.75 && windowWidth < 48)
{
alert(/^\d{2}\.[00]$/.test(windowWidth));
alert(/^\d{2}\.[25]$/.test(windowWidth));
alert(/^\d{2}\.[50]$/.test(windowWidth));
alert(/^\d{2}\.[75]$/.test(windowWidth));
}
else
{
alert("error");
exit;
}
}
Remove [ and ], that is used for character class in regex:
alert(/^\d{2}\.(?:00|25|50|75)$/.test(windowWidth));
For ex: [00] means match literal 0 or 0
OR [25] means match 2 or 5
You could probably combine them to test if they fell within your range and then used the following regex :
/^\d{2}\.(00|25|50|75)$/
You do not need a regular expression for this. You can simply use math expressions.
var n = 35.23;
n >= 16.75 && n <= 48 && !(n % .25); //false
n = 35.25;
n >= 16.75 && n <= 48 && !(n % .25); //true
Here is a non-regex way of doing it, which is possibly more efficient and less messy:
var has25decimal = (windowWidth * 100) % 25 == 0
The % (modulo) gives you the remainder after the number has been divided by 25. When that is 0 the number can be divided by 25.
If you can use html 5 input attributes, then you could try this (without regular expressions):
<input type="number" id="windowWidth" onchange="basePrice()" min="16.75" max="48" step="0.25">
This would enforce the minimum and maximum and change by 0.25 when clicking the up or down arrows.

regex for javascript pattern match

i'm looking for a regex expression or javascript which alerts me when a number is NOT between 48-47 or NOT between 96-105 or IS NOT 110 OR 190 OR 8 OR 13.
thanks for all the help friends !!
Regex is not appropriate for such specific numeric checks. Just do a few if statements to compare the value you're working with to the specific values and ranges you want to exclude.
var number = 19;
alert('Number is'+(numberIsValid(number) ? 'valid' : 'not valid'));
function numberIsValid(number) {
// test for numeric argument
if ((number - 0) != number)
return false;
// test for specific exclusions
if (number == 110 || number == 190 || number == 8 || number == 13 || number == 48 || number == 47)
return false;
// test for excluded range
if (number >= 96 && number <= 105)
return false;
return true;
}
I agree with Chris's response above, if you want to see what it would look like, it is kind of a mess. I wouldn't really recommend you use this.
Just to rephrase: Number may not be 8,13,47,48,96-105,110
var num = 10;
if (! /^(8|13|47|48|9[6-9]|10[0-5]|110)$/.test(num)) {
alert(num);
}
function allowedIntegers(n){
return !/^([^\d]|8|13|47|48|110|190|96|97|98|99|100|101|102|103|104)$/.test(String(n));
}

Best way to alphanumeric check in JavaScript

What is the best way to perform an alphanumeric check on an INPUT field in JSP? I have attached my current code
function validateCode() {
var TCode = document.getElementById("TCode").value;
for (var i = 0; i < TCode.length; i++) {
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if ((cc > 47 && cc < 58) || (cc > 64 && cc < 91) || (cc > 96 && cc < 123)) {
} else {
alert("Input is not alphanumeric");
return false;
}
}
return true;
}
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
You can use this regex /^[a-z0-9]+$/i
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
To match all Unicode letters and numbers you can use a Unicode regex:
const alphanumeric = /^[\p{L}\p{N}]*$/u;
const valid = "Jòhn꠵Çoe日本語3rd"; // <- these are all letters and numbers
const invalid = "JohnDoe3rd!";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
In the above regex the u flag enables Unicode mode. \p{L} is short for \p{Letter} and \p{N} is short for \p{Number}. The square brackets [] surrounding them is a normal character class, meaning that a character must be either a letter or a number (in this context). The * is "zero or more", you can change this into + (one or more) if you don't want to allow empty strings .^/$ matches the start/end of the string.
The above will suffice most cases, but might match more than you want. You might not want to match Latin, Arabic, Cyrillic, etc. You might only want to match Latin letters and decimal numbers.
const alphanumeric = /^[\p{sc=Latn}\p{Nd}]*$/u;
const valid = "JòhnÇoe3rd";
const invalid = "Jòhn꠵Çoe日本語3rd";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
\p{sc=Latn} is short for \p{Script=Latin}. \p{Nd} is short for \p{Decimal_Number} and matches decimals. The difference with \d is that \p{Nd} does not only match 5, but also 𝟓, 5 and possibly more.
Checkout the regex Unicode documentation for details, available \p options are linked on the documentation page.
Note that the u flag is not supported by Internet Explorer.
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
Here are some notes: The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. This is not right.
If I want to check if my "00000" string is alphanumeric, my intuition is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my intuition
is still FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax [] indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguously
processes an alphanumeric string. I called it like PHP relative function ctype_alnum (edit 2020-02-18: Where, however, this checks OR and not AND).
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; // I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true) {
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): // check if A-Z or a-z
isAlpha = true;
break;
default:
// not 0-9, not A-Z or a-z
return false; // stop function with false result, no more checks
}
}
return isNumeric && isAlpha; // return the loop results, if both are true, the string is certainly alphanumeric
}
And here is a demo:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
loop1:
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
$("#input").on("keyup", function(){
if ($(this).val().length === 0) {$("#results").html(""); return false};
var isAlphaNumeric = ctype_alnum ($(this).val());
$("#results").html(
(isAlphaNumeric) ? 'Yes' : 'No'
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div> is Alphanumeric?
<span id="results"></span>
</div>
This is an implementation of Michael Martin-Smucker's method in JavaScript.
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
In a tight loop, it's probably better to avoid regex and hardcode your characters:
const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
return CHARS.has(char);
}
To check whether input_string is alphanumeric, simply use:
input_string.match(/[^\w]|_/) == null
If you want a simplest one-liner solution, then go for the accepted answer that uses regex.
However, if you want a faster solution then here's a function you can have.
console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false
/**
* Function to check if a character is alpha-numeric.
*
* #param {string} c
* #return {boolean}
*/
function isAlphaNumeric(c) {
const CHAR_CODE_A = 65;
const CHAR_CODE_Z = 90;
const CHAR_CODE_AS = 97;
const CHAR_CODE_ZS = 122;
const CHAR_CODE_0 = 48;
const CHAR_CODE_9 = 57;
let code = c.charCodeAt(0);
if (
(code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
(code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
(code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
) {
return true;
}
return false;
}
/**
* Function to check if a string is fully alpha-numeric.
*
* #param {string} s
* #returns {boolean}
*/
function isAlphaNumericString(s) {
for (let i = 0; i < s.length; i++) {
if (!isAlphaNumeric(s[i])) {
return false;
}
}
return true;
}
const isAlphaNumeric = (str) => {
let n1 = false,
n2 = false;
const myBigBrainString =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const myHackyNumbers = "0123456789";
for (let i = 0; i < str.length; i++) {
if (myBigBrainString.indexOf(str.charAt(i)) >= 0) {
n1 = true;
}
if (myHackyNumbers.indexOf(str.charAt(i)) >= 0) {
n2 = true;
}
if (n1 && n2) {
return true;
}
}
return n1 && n2;
};
Works till eternity..
Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal
function isAlphaNumeric ( str ) {
/* Iterating character by character to get ASCII code for each character */
for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
/* Collecting charCode from i index value in a string */
code = str.charCodeAt( i );
/* Validating charCode falls into anyone category */
if (
( code > 47 && code < 58) // numeric (0-9)
|| ( code > 64 && code < 91) // upper alpha (A-Z)
|| ( code > 96 && code < 123 ) // lower alpha (a-z)
) {
continue;
}
/* If nothing satisfies then returning false */
return false
}
/* After validating all the characters and we returning success message*/
return true;
};
console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
(/[^0-9a-zA-Z]/.test( "abcdeFGh123456" ));
Convert string to alphanumeric (Usefull in case of files names)
function stringToAlphanumeric(str = ``) {
return str
.split('')
.map((e) => (/^[a-z0-9]+$/i.test(e) ? e : '_'))
.join('')
}
const fileName = stringToAlphanumeric(`correct-('"é'è-///*$##~~*\\\"filename`)
console.log(fileName)
// expected output "correct_filename"

Categories

Resources