JavaScript RegExp test returns wrong value - javascript

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.

Related

javascript expression expected

I am still new a Javascript tried earching and tried the development tool in Chrome, too see if I could find the problem.
Working in Intellij IDEA 13, Java, javascript and xhtml.
My problem is that I have a piece of javascript, then in IDEA when moused over, says that
Expression Expected
the javascript code looks the following
<script type="text/javascript>
function nameOfFunction(){
if(#{trendAnalysisLocationReportController.model.showTargetLine}){
this.cfg.series[this.cfg.data.length-1].pointLabels = {
show: false
};
}
}
<\script>
the method in the if sentence is a java method with a boolean return value.
the error is shown when hovering
'#{'
if Had a look at the following questions, before :
Expected Expression
boolean in an if statement
But didnt get me a solution.
what Iam I doing wrong ?
It looks as though the problem is the part that you've got within the #{...} block. Without knowing the context, it's hard to be sure, but is this something in a view/JSP page that's supposed to be replaced with a property at runtime? The if block will expect the part inside the brackets to be a boolean value, so if that's rendered to either 'true' or 'false' it would execute at runtime but would likely show the error you're seeing in your IDE as it's not actually a valid piece of JavaScript. If, on the other hand, you're expecting to be able to call your Java method/property from your JavaScript code, you're going to need to do something that requests that value from the server-side code - AJAX or similar.
Also worth noting that we can't see what this.cfg is supposed to represent. If that's your entire script block, then there's nothing that defines the cfg object within the current scope.
One last thing, you should change the <\script> end element to as it won't be understood properly by some browsers.

Breezejs Double trouble in angularjs

I am trying to change a value in a angular view from a integer to a float/double value that is bind to ngmodel. The input don’t except anything other than a integer.
My guess is that breeze does something in the background to validate the value or something on the "defined properties". But my knowledge of JavaScript prototyping is very limiting aka I need to learn it..
This is really hard to explain so I created a plunk that can hopefully help: http://plnkr.co/edit/Gcj0VvBE3f8DRbIjMtqt?p=preview
In the plunk I also added a normal object to test the same values and it is working as expected when changing the numbers to floats/doubles.
So the question is why won’t the value changed when binding to a float/double value from breeze?
I've checked a preliminary fix into GitHub for this. Please check it out and let me know if it works ( or not). We are still testing it.
This issue is caused by Angular's (new) behavior where if the angular digest cycle does not see a change to a model property then it seems to reset the UI to what it was on the previous digest cycle. So.. the idea behind this fix is to convince angular that the model value has changed even when it hasn’t.
and.. nice catch ( this was not obvious and your plunkr helped) :)
Ward adds: You must love the breeze team responsiveness :-) Jay jumped right on this and came up with an interesting solution. But please note the word "preliminary" in Jay's answer. We are discussing this "fix" internally and it may be withdrawn. Consider the zEquivalent directive in this new plunker or just wait until the dust settles.
Update 12 March
I found what I believe is a better solution for your use case because it does not involve "debouncing" nor any change to Breeze. See the zEquivalent directive in this new plunker
Reminder: the "best" resolution of the problem you discovered is still up in the air within the Breeze core team. You should not lock into a particular outcome until we can make a more definitive recommendation.
p.s.: I should have mentioned that Jay and I are on the Breeze core team. We are doing our best to get you out of a jam but sometimes we move a wee too quickly. Bear with us please.
This answer deprecated as of 12 March
Leaving it here for "historical" purposes.
I think you should try the zEquivalent directive first.
It is important to know that the Angular team is working on a robust extension to data binding that includes "debounce" which is still a good idea for many scenarios. See this (long) pull request thread on the Angular GitHub site.
Original Answer
Consider the zDebounce directive currently located in this plunker which is based on #qorsmond's second attempt.
I'd like to know your thoughts. I'm inclined to call this "the solution" and to add it to Breeze Labs. I'll update this answer when/if I do add it to the labs.
you can use input type="number" step="any" and hide the arrows using css
I tracked down the behaviour in the breeze code, when the value change it is intercepted and parsed:
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val = parseFloat(src);
return isNaN(val) ? source : val;
}
return source;
};
So when the value change this function is called that parse the string to a float, the problem is as soon as the value entered is some number and a point like 5. it parse it to the number 5 witch is obviously correct. So you will never be able to get past the point.
When changing the input to a number type it works because its sourceTypeName is not a string.
Update
I ended up changing the breeze code to enable the decimal to be entered, I’m still not sure if I missed something but this works for me.
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val;
if (src.indexOf('.', src.length - 1) !== -1) {
val = src;
}
else {
val = parseFloat(src);
}
return isNaN(val) ? source : val;
}
return source;
};
This doesn't work for large or small numbers that might be entered using an exponent form. If I want to enter 2.55e35 (a large salary ;)) the current implementation stops at the 'e'. Is there an easy way to fix this?

Object has no method 'charAt' in jQuery plugin

I am attempting to use the autoNumeric jQuery plug-in which helps with the conversion of various currencies in jQuery.
The plug-in itself works when I use it in a jsFiddle example.
$(function () {
$('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
However, as soon as I integrate it into a big, legacy project, I start receiving the above error on line 194. I know why I'm getting the error - a string is not being passed into the negativeBracket function (negativeBracket(s, nBracket, oEvent) is the signature). Instead, it seems to be a jQuery object - e.fn.init1. I'm confused on how this might be happening. I realize the community may not be able to give a direct answer, but I would love (and will accept as an answer) being pointed in the right direction as nothing has jumped out at me so far.
Update
So, have some additional info that may be of help. It still has me stumped how it's happening (unfortunately, the answers below didn't help to provide any additional insight). When I link in autoNumeric, I key it off of any text field with the class money. It does work as I am typing in the box. I can see see formatting. However, when I tab into a new box, the box I just finished typing in clears itself completely after hitting line 152 in autoNumeric with the same exact error.
#Carlos487 was correct in his answer when he said I have an object that is not a string. I instead have an object that, I believe, is a function. Here's what I'm seeing in Chrome debugger tools:
e.fn.init[1]
> 0: input#price.money required
> context: input#price.money required
length: 1
selector: ""
> __proto__: Object[0]
The "arrowed" items can be further expanded out. I don't know if this provides any more clues, but it's at least something a bit different.
The errors like
no method XXXXX in Object
are produced because you are trying to call obj.XXXX() and obj is not of the desired type, in your particular case a string.
Have you tried in another browser because older or IE can be a little troublesome. I would recomend using chrome developer tools with your legacy app to see if anything else is conflicting or producing the error
I will bet money that you are using a second library which is interfering with jQuery. It has probably overridden $ with its own function.
Try using jQuery instead of $:
jQuery(function () {
jQuery('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
It turns out that the issue was a myriad of issue compounding into the error I saw. A couple things that was happening:
The validator plug-in was wrapping the jQuery object in its own structure (hence the charAt issue).
Once I fixed that, I also learned that some homegrown code was also wiping and rewriting data into the field to provide formatting (which is what autoNumeric is also doing), so autoNumeric would bomb out because it would get a null value and attempt to format it.
There was some other random craziness that also needed cleaned up. So...issue resolved! Still more to work on, but at least this hurdle is past. Thanks all for your help.

JavaScript my function to test a password doesn't work

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.

JavaScript string comparison fails randomly

I’m having a pretty weird bug occurring in my JS application on a random basis. Basically, the script fails to accurately compare two strings. More specifically, at times does not see two identical strings as identical: ('blah' == 'blah') returns false.
The funny thing is that on another try, the same two strings may be admitted to be identical (statement returns true). I never managed to figure out the pattern. I’ve also tried to use === instead of ==; this didn’t help.
I couldn’t think of a better way to demonstrate and prove this ridiculous bug other than by recording a screencast. So here it is: http://www.screenr.com/klOs. I keep giving correct answers for each quiz in that video, but closer to the end you will how my answers for ‘Japan’ and ‘Taiwan’ will be regarded as ‘wrong’; the console will also show the given answer string, the correct answer string, and the result of their comparison (false ?!!).
So what could possibly be the reason for this odd behaviour and how do I get around fixing it?
You can see the code with the comparison statement in the screencast. The ‘params.givenAnswer’ comes directly from the button text label:
//*** Options for answering the card quiz
quizOptions = new Ext.Panel({
id: 'quizOptions',
[…………]
listeners: {
el: {
scope: this,
tap: this.checkAnswer
}
}
});
checkAnswer: function(container, element) {
// Get the text value of the button clicked
var answer = Ext.fly(element).dom.innerText;
Ext.dispatch({
controller: 'Practice',
action: 'checkAnswer',
givenAnswer: answer
});
},
UPDATE Thank you #JAAulde and #Mike! I’ve tried to include the quotes and the var type in the logging and I got this result:
Now it’s clear why the string comparison fails: there seem to be an extra line break of sorts in the first string. It’s still very weird, since it didn’t not appear as a blank new line in the previous logging, and most importantly, it appears there randomly (notice how ‘Taiwan’ was accepted this time without any problems).
I’ve included a simple line-break removal rule for the answer strings, and now everything seem to be working fine. Thanks a lot everyone!
Using === is a strict equality comparison. This means that the data type and the contents are being compared. They both (data and type) must be the same to equal and return true.
When you switched your strict comparison to == the test should have worked even though the data types were different. It failed however because of the extra blank spaces.

Categories

Resources