passsword validation and alert message in Installshield javascript - javascript

Can anyone tell me how to print a message in installshield supported javascript instead of alert?
I tried with the below code but alert is'nt working.
And another problem is that I am unable to validate password by using RegExp.
function Passwordvalidation()
{
var password= Session.Property("PASSWORD");
var patt = new RegExp(":\\[A-Za-z0-9]{6,20}$\\","ig");
var validpassword = patt.test(password);
if(validpassword)
{
GetMD5(); //calls another function
return true;
}
alert("password should have 6 to 20 characters which contains alphabets and digits between 0 to 9");
return false;
}

As #some suggested, you should first only check if the regex works.
But reading the error message "password should have 6 to 20 characters which contains alphabets and digits between 0 to 9" , I think that this part of the regex [A-Za-z0-9]{6,20}$ does not do what you think it does.
This matches any uppercase or lowercase character or digit repeated between 6 and 20 times at the end of the string.
This would also match $$$$$444444 or aaaaaa
For example:
var patt = new RegExp('[a-z0-9]{6,20}$', "i");
var passwords = [
"aaaaaa",
"333333",
"a12b3c",
"AAAAAA",
"$$$$$444444"
];
for (var i = 0; i < passwords.length; i++) {
console.log(passwords[i] + " : " + patt.test(passwords[i]));
}
With ^:
var patt = new RegExp('^[a-z0-9]{6,20}$', "i");
var passwords = [
"aaaaaa",
"333333",
"a12b3c",
"AAAAAA",
"$$$$$444444"
];
for (var i = 0; i < passwords.length; i++) {
console.log(passwords[i] + " : " + patt.test(passwords[i]));
}
The modifier i makes it case insensitive, so you could update your regex to [a-z0-9]{6,20}$ or [A-Z0-9]{6,20}$
You can also omit the g modifier to prevent wrong results.

It is probably because var patt = new RegExp(":\\[A-Za-z0-9]{6,20}$\\","ig"); throws an exception since that is an illegal regexp.
You don't need to use new RegExp but can define it as a literal regexp:
var patt = /^[A-Za-z0-9]{6,20}$/;
Since you defined ranges A-Z and a-z you don't need the i flag, and you don't need the g flag either.

This answer explains password restriction validation with regex really nicely:
Let's say that we want our password to:
Contain between 8 and 15 characters
Must contain an uppercase letter
Must contain a lowercase letter
Must contain a digit
Must contain one of special symbols
Then we can write a regex like this:
^(?=.{8,15}$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*]).*$
\__________/\_________/\_________/\_________/\______________/
length upper lower digit symbol

Related

Js Regex only allowed characters one occurence

Trying the regex very hard but could not get the desired result.
Must begin with numbers and maximum of 4
followed by only one allowed alphabet
Please have a look at below code.
var strings = [
'1h', //should match
'13s', //should match
'30m', //should match
'42hr', //should not match
'8 hours ', //should not match
'765765', //should not match
'5sec', //should not match
'23445345345s', //should not match
'335m' //should match
];
for (var i = 0; i < strings.length; i++)
{
var match = strings[i].match(/\d{4}[h|m|s]{1}/g);
console.log(strings[i], (match ? "Match" : "Not match"));
}
You regex should be:
/^\d{1,4}[hms]$/gm
First, you require 4 digits with d{4}
Change it to d{1,4} to be one to four digits
Then add a $ to indicate the end of the string, so it doesn't allow more characters after the letter
Check out Regex101, Really useful for testing and understanding regex
I've added a ^ to match from start
strings.filter(x => x.match(/^\d{1,4}[hms](?!\w)/g) )

Remove leading and trailing characters from a

I have a text file which has strings separated by whitespace. The text file contains some special characters (latin, currency, punctuations etc.) Which need to be discarded from final output. Please note that legal characters are all characters in Unicode except these special characters.
We need to separate/split text by whitespaces and then remove only leading and trailing special characters. If special characters are in between two legal characters then we won't remove them.
I can easily do it in two phases. Split text by whitespaces and then remove only leading and trailing special characters from each string. However, I need to process string only once. Is there any way, it could be achieved in one pass. Note: We can't use RegEx.
For this question assume that these characters are special:
[: , ! . < ; ' " > [ ] { } ` ~ = + - ? / ]
Example:
:!/,.<;:.?;,BBM!/,.<;:.?;,` IS TALKING TO `B!?AM!/,.<;:.?;,
Here output would be an array of valid strings: ["BBM", "IS", "TALKING", "TO", "B!?AM"]
Make simple state machine (finite automata)
Walk in a loop through all chars
At every step check if current char is letter, space or special
Execute some operation (perhaps empty) depending on state and char kind
Change state if needed
for example, you may stay in "special" state until letter is met. Remember starting index of the word and make state "inside word". Continue until special char or space is met (it is still not clear from your question).
I have used typescript and have done it in a single pass.
Please note that isSpecialCharacterCode(charCode) function simply checks whether unicode of text character is same as unicode of provided special characters.Same is true for isWhitespaceCode(charCode) function.
parseText(text: string): string[]{
let words : string[] = [];
let word = "";
let charCode = 1;
let haveSeenLegalChar = false; //set it if we have encountered legal character in text
let seenSpecialCharsToInclude = false; //set it if we have encountered //special character in text
let inBetweenSpecialChars = ""; // string containing special chars //which may be included in between legal word
for(let index = 0; index < text.length; index++){
charCode = text.charCodeAt(index);
let isSpecialChar = isSpecialCharacterCode(charCode);
let isWhitespace = isWhitespaceCode(charCode);
if(isSpecialChar && !isWhitespace){
//if this is a special character then two cases
//first is: It can be part of word (it is only possible if we have already seen atleast one legal character)
//Since it can be part of word but we are not sure whether this will be part of word so store it for now
//second is: This is either leading or trailing special character..we should not include these in word
if(haveSeenLegalChar){
inBetweenSpecialChars += text[index];
seenSpecialCharsToInclude = true;
}else{
//since we have not seen any legal character till now so it must be either leading or trailing special chars
seenSpecialCharsToInclude = false;
inBetweenSpecialChars = "";
}
}else if(isWhitespace){
//we have encountered a whitespace.This is either beginning of word or ending of word.
//if we have encountered any leagl char, push word into array
if(haveSeenLegalChar){
words.push(word);
word = "";
inBetweenSpecialChars = "";
}
haveSeenLegalChar = false;
}else if(!isSpecialChar){
//legal character case
haveSeenLegalChar = true;
if(seenSpecialCharsToInclude){
word += inBetweenSpecialChars;
seenSpecialCharsToInclude = false;
inBetweenSpecialChars = "";
}
word += text[index];
}
}
return words;
}

How to ban words with diacritics using a blacklist array and regex?

I have an input of type text where I return true or false depending on a list of banned words. Everything works fine. My problem is that I don't know how to check against words with diacritics from the array:
var bannedWords = ["bad", "mad", "testing", "băţ"];
var regex = new RegExp('\\b' + bannedWords.join("\\b|\\b") + '\\b', 'i');
$(function () {
$("input").on("change", function () {
var valid = !regex.test(this.value);
alert(valid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='word_to_check'>
Now on the word băţ it returns true instead of false for example.
Chiu's comment is right: 'aaáaa'.match(/\b.+?\b/g) yelds quite counter-intuitive [ "aa", "á", "aa" ], because "word character" (\w) in JavaScript regular expressions is just a shorthand for [A-Za-z0-9_] ('case-insensitive-alpha-numeric-and-underscore'), so word boundary (\b) matches any place between chunk of alpha-numerics and any other character. This makes extracting "Unicode words" quite hard.
For non-unicase writing systems it is possible to identify "word character" by its dual nature: ch.toUpperCase() != ch.toLowerCase(), so your altered snippet could look like this:
var bannedWords = ["bad", "mad", "testing", "băţ", "bať"];
var bannedWordsRegex = new RegExp('-' + bannedWords.join("-|-") + '-', 'i');
$(function() {
$("input").on("input", function() {
var invalid = bannedWordsRegex.test(dashPaddedWords(this.value));
$('#log').html(invalid ? 'bad' : 'good');
});
$("input").trigger("input").focus();
function dashPaddedWords(str) {
return '-' + str.replace(/./g, wordCharOrDash) + '-';
};
function wordCharOrDash(ch) {
return isWordChar(ch) ? ch : '-'
};
function isWordChar(ch) {
return ch.toUpperCase() != ch.toLowerCase();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='word_to_check' value="ba">
<p id="log"></p>
Let's see what's going on:
alert("băţ".match(/\w\b/));
This is [ "b" ] because word boundary \b doesn't recognize word characters beyond ASCII. JavaScript's "word characters" are strictly [0-9A-Z_a-z], so aä, pπ, and zƶ match \w\b\W since they contain a word character, a word boundary, and a non-word character.
I think the best you can do is something like this:
var bound = '[^\\w\u00c0-\u02c1\u037f-\u0587\u1e00-\u1ffe]';
var regex = new RegExp('(?:^|' + bound + ')(?:'
+ bannedWords.join('|')
+ ')(?=' + bound + '|$)', 'i');
where bound is a reversed list of all ASCII word characters plus most Latin-esque letters, used with start/end of line markers to approximate an internationalized \b. (The second of which is a zero-width lookahead that better mimics \b and therefore works well with the g regex flag.)
Given ["bad", "mad", "testing", "băţ"], this becomes:
/(?:^|[^\w\u00c0-\u02c1\u037f-\u0587\u1e00-\u1ffe])(?:bad|mad|testing|băţ)(?=[^\w\u00c0-\u02c1\u037f-\u0587\u1e00-\u1ffe]|$)/i
This doesn't need anything like ….join('\\b|\\b')… because there are parentheses around the list (and that would create things like \b(?:hey\b|\byou)\b, which is akin to \bhey\b\b|\b\byou\b, including the nonsensical \b\b – which JavaScript interprets as merely \b).
You can also use var bound = '[\\s!-/:-#[-`{-~]' for a simpler ASCII-only list of acceptable non-word characters. Be careful about that order! The dashes indicate ranges between characters.
You need a Unicode aware word boundary. The easiest way is to use XRegExp package.
Although its \b is still ASCII based, there is a \p{L} (or a shorter pL version) construct that matches any Unicode letter from the BMP plane. To build a custom word boundary using this contruct is easy:
\b word \b
---------------------------------------
| | |
([^\pL0-9_]|^) word (?=[^\pL0-9_]|$)
The leading word boundary can be represented with a (non)capturing group ([^\pL0-9_]|^) that matches (and consumes) either a character other than a Unicode letter from the BMP plane, a digit and _ or a start of the string before the word.
The trailing word boundary can be represented with a positive lookahead (?=[^\pL0-9_]|$) that requires a character other than a Unicode letter from the BMP plane, a digit and _ or the end of string after the word.
See the snippet below that will detect băţ as a banned word, and băţy as an allowed word.
var bannedWords = ["bad", "mad", "testing", "băţ"];
var regex = new XRegExp('(?:^|[^\\pL0-9_])(?:' + bannedWords.join("|") + ')(?=$|[^\\pL0-9_])', 'i');
$(function () {
$("input").on("change", function () {
var valid = !regex.test(this.value);
//alert(valid);
console.log("The word is", valid ? "allowed" : "banned");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>
<input type='text' name='word_to_check'>
In stead of using word boundary, you could do it with
(?:[^\w\u0080-\u02af]+|^)
to check for start of word, and
(?=[^\w\u0080-\u02af]|$)
to check for the end of it.
The [^\w\u0080-\u02af] matches any characters not (^) being basic Latin word characters - \w - or the Unicode 1_Supplement, Extended-A, Extended-B and Extensions. This include some punctuation, but would get very long to match just letters. It may also have to be extended if other character sets have to be included. See for example Wikipedia.
Since javascript doesn't support look-behinds, the start-of-word test consumes any before mentioned non-word characters, but I don't think that should be a problem. The important thing is that the end-of-word test doesn't.
Also, putting these test outside a non capturing group that alternates the words, makes it significantly more effective.
var bannedWords = ["bad", "mad", "testing", "băţ", "båt", "süß"],
regex = new RegExp('(?:[^\\w\\u00c0-\\u02af]+|^)(?:' + bannedWords.join("|") + ')(?=[^\\w\\u00c0-\\u02af]|$)', 'i');
function myFunction() {
document.getElementById('result').innerHTML = 'Banned = ' + regex.test(document.getElementById('word_to_check').value);
}
<!DOCTYPE html>
<html>
<body>
Enter word: <input type='text' id='word_to_check'>
<button onclick='myFunction()'>Test</button>
<p id='result'></p>
</body>
</html>
When dealing with characters outside my base set (which can show up at any time), I convert them to an appropriate base equivalent (8bit, 16bit, 32bit). before running any character matching over them.
var bannedWords = ["bad", "mad", "testing", "băţ"];
var bannedWordsBits = {};
bannedWords.forEach(function(word){
bannedWordsBits[word] = "";
for (var i = 0; i < word.length; i++){
bannedWordsBits[word] += word.charCodeAt(i).toString(16) + "-";
}
});
var bannedWordsJoin = []
var keys = Object.keys(bannedWordsBits);
keys.forEach(function(key){
bannedWordsJoin.push(bannedWordsBits[key]);
});
var regex = new RegExp(bannedWordsJoin.join("|"), 'i');
function checkword(word) {
var wordBits = "";
for (var i = 0; i < word.length; i++){
wordBits += word.charCodeAt(i).toString(16) + "-";
}
return !regex.test(wordBits);
};
The separator "-" is there to make sure that unique characters don't bleed together creating undesired matches.
Very useful as it brings all the characters down to a common base that everything can interact with. And this can be re-encoded back to it's original without having to ship it in key/value pair.
For me the best thing about it is that I don't have to know all of the rules for all of the character sets that I might intersect with, because I can pull them all into a common playing field.
As a side note:
To speed things up, rather than passing the large regex statement that you probably have, which takes exponentially longer to pass with the length of the words that you're banning, I would pass each separate word in the sentence through the filter. And break the filter up into length based segments. like;
checkword3Chars();
checkword4Chars();
checkword5chars();
who's functions you can generate systematically and even create on the fly as and when they become required.

Regular Expression: password must contain at least 1 special character

I am trying to verify that the password inserted by the user has atleast 1 special character in it. Can anyone help me with the regExp?
var password = document.getElementById(.....).value;
var special = new RegExp("?????");
if(special.test(password)){
......
}
I consider all the non-word characters as special characters.
var special = new RegExp("^.*?\\W");
OR
var special = /^.*?\W/;
use this way.
var passwd = document.getElementById('password').value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/);
if (pattern.test(passwd)) {
// code goes here
}

regular expression of number and letters mix

My account must have number and letters.And its length range 4 and 8.
It's not only number and it's not only letters.
Right ex: a111 ,1a1bb, aa111a, 111aaa. Error ex: abcdef, 12345, a123!.
How can I write the Regular Expression.
I tried write that:([a-z]+[0-9]+[a-z]*){4,10}|([0-9]+[a-z]+[0-9]*){4,10}.
But it's not match. Where is my error?
Try this: update ^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,20})$
Here
^(
(?=.*\d) // must contains one digit from 0-9
(?=.*[a-zA-Z]) //must contains one lowercase Uppercase characters
[a-zA-Z0-9] //match any letter or number previous condition checking
{4,20} //length at least 4 characters and maximum of 20
)$
Live demo
Try this:
/^(?=.[a-z]+[0-9]|[0-9]+[a-z].)[a-zA-Z\d*]{4,8}$/
var filter = /^(?=.*[a-z]+[0-9]|[0-9]+[a-z].*)[a-zA-Z\d*]{4,8}$/;
var vals = "11aa11";
if (filter.test(vals)){
alert('working');
}else {
alert('not working');
}
Try this
var patt = new RegExp("(([A-Za-z][0-9]) |([0-9][A-Za-z])) ([A-Za-z]*[0-9]*){2,6}");
var res = patt.exec(test_str);

Categories