JavaScript my function to test a password doesn't work - javascript

function demoMatchClick() {
var validString = /^[a-z](?=[a-z]*[0-9])[a-z0-9]{0,6}[a-z]$/
var re = new RegExp(validString);
if (document.form1.subject.value.test(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
<INPUT TYPE=SUBMIT VALUE="Replace" ONCLICK="demoReplaceClick()">
I can't get it to popup an Alert to pop up
I want these rules to be enforced
•Not have upper-case letters.
•Begin with a letter.
•Have at least 1 digit(s) not at the beginning and end.
•Have up to 8 alphanumeric
•Does NOT have any symbols like ##$ characters (symbols like !##$%^&*()-+).
I am using a button to execute the code for now.

Well, I suppose this regex suits your rules...
var rules = /^[a-z](?=[a-z]*[0-9])[a-z0-9]{0,6}[a-z]$/;
But I think there are several issues with your code, which I'd like to point out. Don't take it as a personal offense, please: believe me, I'm actually saving you a LOT of time and nerves.
First, there's a standard rule: each function should do only one thing - but do it really well (or so they say, these perfectionists!). Your code is too tightly coupled with DOM extraction: I was really surprised when it failed to work when pasted in my environment! Only then I noticed that document.forms call. It's not really needed here: it's sufficient to build a function taking one parameter, then call this function with the value extracted somewhere else. This way, btw, you can easily separate the causes of errors: it would be either in DOM part, or within the function.
Second, Regexes are really very close to be considered first-class citizens in JavaScript (not so as in Perl, but still much closer than in some other languages). That means you can write the regex literals as is, and use it later - without new Regexp constructs.
With all that said, I'd write your code as...
function validatePassword(password) {
var rules = /^[a-z](?=[a-z]*[0-9])[a-z0-9]{0,6}[a-z]$/;
return rules.test(password);
}
... then use it by something like ...
var password = document.form1.subject.value;
alert( validatePassword(password) ? 'Success! :)' : 'Failure... :(' );
P.S. And yes, Riccardo is right: set too strict rules for passwords - and suffer the consequences of narrowing the range of search for an attacker. And it's quite easy to see the validation rules set in Javascript: even obfuscators won't help much.

Here is the modified code:
function demoMatchClick(input) {
var validString = /^[a-z](?=[a-z]*[0-9])[a-z0-9]{0,6}[a-z]$/;
if (validString.test(input)) {
alert("Successful match");
} else {
alert("No match");
}
}
demoMatchClick("hello world");
validString variable is already a RegExp object and you can use it directly, additionally .test() method belongs to regex object not to string.

Related

JavaScript RegExp test returns wrong value

I am solving curious problem right now. I am testing a string with regexp and it returns false eventhough it should return true. I am implementing it in javascript. I have this function
function isPhoneNumberValid(phoneNumber) {
return /^\+\d{12}$/.test(phoneNumber);
}
phoneNumber is a variable in format of + and 12 numbers after (+421123123123 for example). I've played around with different versions of regexp like /^\+[0-9]{12}$/.
According to sites like https://www.regextester.com/21 my regexp should be working for the format I want, yet it returns false still. When I tried testing this regexp /^\+[0-9]/ it returned true when only +3 was written, I guess the problem is with the numbers count?
Parameter phoneNumber received in the function is correct one so I don't think the mistake is there. Also no combination of modifiers helped.
Here is a log of this function
function isPhoneNumberValid(phoneNumber) {
console.log('ph:'+phoneNumber);
console.log(/^\+\d{12}$/.test(phoneNumber));
}
To give you more insight I have a input type text with class .phoneNumber, then I have jquery function watching keyup event, it looks like this
$('.phoneNumber').on('keyup', function() {
if (isPhoneNumberValid($(this).val())) {
console.log('is valid');
} else {
console.log( 'invalid');
}
});
Other function you've already seen above. I tried wrapping values in String(), too.
I am trying to clarify why live example in online environment is for no good, since I know this code works in there as I already stated before. The question is aimed more to what could possibly make it go this way, since the exact same copy works in codepen, yet doesn't work in my project.
The problem was with latte template engine. It needed to have
<script n:syntax="double"></script>
to work.

Javascript: Website url validation with regex

I'm working on create a regular expression in javascript to validate website urls. I searched a bit in the stackoverflow community and i did not find something to be completed helpful.
My regex until now: /(https?:\/\/)?(www\.)?[a-zA-Z0-9]+\.[a-zA-Z]{2,}/g
But it seems to fail and pass the validation for the url with two w like ww.test.com
Should pass the test of regex:
http://www.test.com
https://www.test.com
www.test.com
www.test.co.uk
www.t.com
test.com
test.fr
test.co.uk
Should not pass the test of regex:
w.test.com
ww.test.com
www.test
test
ww.test.
.test
.test.com
.test.co.ul
.test.
Any suggestions or thoughts?
Even if this answer is a bit too much for this Problem, it illustrates the problem: Even if it might be possible to create a regexp to check the url, it is much simpler and more robust to parse the URL and "create a real Object", on/with which the overall test can be decomposed to a number of smaller tests.
So probably the builtin URL constructor of modern browsers may help you here (LINK 1, LINK 2).
One approach to test you url might look like this:
function testURL (urlstring) {
var errors = [];
try {
var url = new URL(urlstring);
if (!/https/.test(url.protocol)) {
errors.push('wrong protocol');
}
//more tests here
} catch(err) {
//something went really wrong
//log the error here
} finally {
return errors;
}
}
if (testURL('mr.bean').length == 0) { runSomething(); }
Here's a non official, but works for most things one with an explanation. This should be good enough for most situations.
(https?:\/\/)?[\w\-~]+(\.[\w\-~]+)+(\/[\w\-~]*)*(#[\w\-]*)?(\?.*)?
(https?:\/\/)? - start with http:// or https:// or not
[\w\-~]+(\.[\w\-~]+)+ follow it with the domain name [\w\-~] and at least one extension (\.[\w\-~])+
[\w\-~] == [a-zA-Z0-9_\-~]
Multiple extensions would mean test.go.place.com
(\/[\w\-~]*)* then as many sub directories as wished
In order to easily make test.com/ pass, the slash does not enforce following characters. This can be abused like so: test.com/la////la.
(#[\w\-]*)? Followed maybe by an element id
(\?.*)? Followed maybe by url params, which (for the sake of simplicity) can be pretty much whatever
There are plenty of edge cases where this will break, or where it should but it doesn't. But, for most cases where people aren't doing anything wacky, this should work.
/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:#\-_=#])*/g

Replacing c# function bij Jquery not working without knowing how to troubleshoot

I'm trying to replace an ASP.NET (C#) server-sided method by an javascript/Jquery method. I'm fairly new to Jquery but all went well until I began with regular expressions.
my code in ASP.NET C#
if ((Regex.Match(postcode.Trim(), #"^[1-9]\d{3} ?[a-zA-Z]{2}$")).Success)
{
return Regex.Replace(postcode.Trim(), #"(^[1-9]\d{3})( ?)([a-zA-Z]{2}$)", "$1$3").ToUpper();
}
else
{
throw new Exception("Postcode incorrect");
}
in Jquery I'm only focussing to replace for the moment by manually input the right strings.
I've created a function like:
function FormatDutchPostalCode() {
var postcode = $("#Text1").val();
postcode = postcode.replace(/(^[1-9]\d{3})( ?)([a-zA-Z]{2}$)/, $1$3);
$("#Text1").val(postcode);
}
I'm getting the value from the textbox, so far so good. But when replacing it seems the browsers exits the function (tested in IE9 and FF10.0.1)
What I'm i doing wrong and is it possible to troubleshoot Jquery/Javascript. I've seen firebug could set breakpoints but I can't find if (and if so which) errors occur.
Here is a port of your C# function to JS. It uses an IIFE in order to cache the regex without polluting the current execution scope.
jsFiddle
var FormatDutchPostalCode = (function() {
var reg = /^([1-9]\d{3})\s?([a-z]{2})$/i;
return function(){
var postcode = $.trim($("#Text1").val());
if (postcode && postcode.match(reg) )
{
return postcode.replace(reg, "$1$2").toUpperCase();
}
else
{
throw new Error("Postcode incorrect");
}
};
}());
You need to use '$1$3' or /$1$3/ for the replacement pattern. Currently you've placed the replacement pattern in without using it as a string or regex pattern.
Check out this jsFiddle link showing a working solution.
You could also simplify your pattern by removing the capture group for the optional space, then you can perform the replace using the existing capture groups:
Pattern: /^([1-9]\d{3}) ?([a-zA-Z]{2})$/
Replacement: '$1$2' (only 2 groups exist)
To use Firebug or developer tools, you should be able to bring the tool up using the F12 key. You can test your replacement directly in the console window, or debug your script from the script tab (select the relevant JavaScript file) and place a breakpoint on the line you're interested in by right clicking and adding it or clicking on the line number on the left.
Check out this article for more details: JavaScript debugging for beginners.

zen-coding: ability to ascend the DOM tree using ^

I forked the excellent zen-coding project, with an idea to implement DOM ascension using a ^ - so you can do:
html>head>title^body>h1 rather than html>(head>title)+body>h1
Initially I implemented with rather shoddy regex methods. I have now implemented using #Jordan's excellent answer. My fork is here
What I still want to know
Are there any scenarios where my function returns the wrong value?
Disclaimer: I have never used zen-coding and this is only my second time hearing about it, so I have no idea what the likely gotchas are. That said, this seems to be a working solution, or at least very close to one.
I am using Zen Coding for textarea v0.7.1 for this. If you are using a different version of the codebase you will need to adapt these instructions accordingly.
A couple of commenters have suggested that this is not a job for regular expressions, and I agree. Fortunately, zen-coding has its own parser implementation, and it's really easy to build on! There are two places where you need to add code to make this work:
Add the ^ character to the special_chars variable in the isAllowedChar function (starts circa line 1694):
function isAllowedChar(ch) {
...
special_chars = '#.>+*:$-_!#[]()|^'; // Added ascension operator "^"
Handle the new operator in the switch statement of the parse function (starts circa line 1541):
parse: function(abbr) {
...
while (i < il) {
ch = abbr.charAt(i);
prev_ch = i ? abbr.charAt(i - 1) : '';
switch (ch) {
...
// YOUR CODE BELOW
case '^': // Ascension operator
if (!text_lvl && !attr_lvl) {
dumpToken();
context = context.parent.parent.addChild();
} else {
token += ch;
}
break;
Here's a line-by-line breakdown of what the new code does:
case '^': // Current character is ascension operator.
if (!text_lvl && !attr_lvl) { // Don't apply in text/attributes.
dumpToken(); // Operator signifies end of current token.
// Shift context up two levels.
context = context.parent.parent.addChild();
} else {
token += ch; // Add char to token in text/attribute.
}
break;
The implementation above works as expected for e.g.:
html>head>title^body
html:5>div#first>div.inner^div#second>div.inner
html:5>div>(div>div>div^div)^div*2
html:5>div>div>div^^div
You will doubtless want to try some more advanced, real-world test cases. Here's my modified source if you want a kick-start; replace your zen_textarea.min.js with this for some quick-and-dirty testing.
Note that this merely ascends the DOM by two levels and does not treat the preceding elements as a group, so e.g. div>div^*3 will not work like (div>div)*3. If this is something you want then look at the logic for the closing parenthesis character, which uses a lookahead to check for multiplication. (Personally, I suggest not doing this, since even for an abbreviated syntax it is horribly unreadable.)
You should look for Perl's Text::Balanced alternative in the language that you're using.

Get variable passed to switch statement

This isn't the exact use scenario but I was wondering if it was possible to get the value passed to the switch statement without having to retype what is in the switch() part.
Example :
switch(someObject.withSomevalue*(Math.random()*11)) {
case 1 : alert("one");
// more cases here
default: alert(theNumberThatWasPassed);
}
If we run the Math.random() again we'll get another random number that very well could meet one of the cases, so calling what aws called in the switch(x) statement isn't an option. I've been just storing it in a variable - x = someObject.withSomevalue*(Math.random()*11) - and then passing it to the switch that way switch(x), but I was wondering if it's possible to get the value passed to the switch within the switch statement.
As everyone else pointed out you have to save it in a variable. But you can do the following in the expression though I do not know how cross browser compatible this is:
switch(x = <your expression>){
//
default:alert(x);
}
and at least you save one line of code.
This is the same as asking if you can find the values for if(Math.random()){...}. The answer is no, because they are language constructs, and not functions.
Just capture it into a variable before the switch and use that variable.
var myValue = someObject.withSomevalue*(Math.random()*11);
switch(myValue) {
case 1 : alert("one");
// more cases here
default: alert(myValue);
}
I would say your best bet would be to do what you currently are doing, and capture it into the variable before the switch statement. Is there any reason you would not want to do this besides saving a line of code?
Interesting... OP, I'm trying to look at your thought process. Maybe just write out the code how you think it should look like (ignoring that it wouldn't work in the first place).
update:
At least in C/C++, you can just form another block to have the var only be accessible within the switch:
...
{
var mySwitchVar = blah;
switch(mySwitchVar) {
case blah blah blah:
default blah blah:
}
}
...

Categories

Resources