Wildcard integer in javascript condition - javascript

I have a section of a form that can be duplicated indefinitely, and I'm attempting to create a validation condition for it (using the ajaxForm plugin, although this aspect is relatively incidental).
The condition looks a bit like this:
if(formData[i].name == 'create-flight[fields][0][scheduled-departure-time]' && formData[i].value == ''){
// Do stuff
}
Note the 0 in create-flight[fields][0][scheduled-departure-time]. This could be a 0, a 1, or even a 37. Importantly I don't need to know, as the function handles everything dynamically and this condition triggers within a foreach, so every field will be checked. Is there a way to add a wildcard here? i.e. create-flight[fields]['+any_integer+'][scheduled-departure-time] ?
Often this would be catered for with an or operator, but it could be any number, so that's not practical.

Have you tried a regex? Try
formData[i].name.match(/^create-flight\[fields\]\[[0-9]+\]\[scheduled-departure-time\]$/)

I suggest you to use regular expressions (http://www.w3schools.com/jsref/jsref_obj_regexp.asp).
I would use something like:
/create-flight\[fields\]\[\d+\]\[scheduled-departure-time\]/
So the final code should look like this:
var patt = new RegExp(/create-flight\[fields\]\[\d+\]\[scheduled-departure-time\]/);
if(patt.test(formData[i].name) && formData[i].value == ''){
// Do stuff
}

You can test this with a regular expression:
var re = new RegExp("^create-flight\[fields\]\[[0-9]+\]\[scheduled-departure-time\]$");
if (re.test(formData[i].name)) {
// ...
}

Related

Is there a possibility to apply different regex var depending on if statement in javascript?

I'm trying to write a function that validates number depending on the country. With each country, using intl-input, I obtain different class. Depending on that class inside the PrestaShop checkout module I am trying to implement the different amount of characters in phone input.
Result is something like this:
function validatePhoneNumber(s)
{
if ($('div').hasClass("opt216")) {
var reg = /^\+(?:[0-9] ?){10}$/;
}else {
var reg = /^\+(?:[0-9] ?){10,14}$/;
}
return reg.test(s);
}
What I have in this is every country has the same amount of characters (10) and if the statement doesn't seem to work. So, I thinking, is making this regex variable and changing it on if statement actually allowed?
Thanks everyone, I figured out what was wrong - i had few opt216 classes in document, so i went another way with attribute selection, something like that
if ($('#iti-item-216').attr('aria-selected') == 'true')

How to user a condition in a String inside an IF sentence

I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}

How to make indexOf only match 'hi' as a match and not 'hirandomstuffhere'?

Basically I was playing around with an Steam bot for some time ago, and made it auto-reply when you said things in an array, I.E an 'hello-triggers' array, which would contain things like "hi", "hello" and such. I made so whenever it received an message, it would check for matches using indexOf() and everything worked fine, until I noticed it would notice 'hiasodkaso', or like, 'hidemyass' as an "hi" trigger.
So it would match anything that contained the word even if it was in the middle of a word.
How would I go about making indexOf only notice it if it's the exact word, and not something else in the same word?
I do not have the script that I use but I will make an example that is pretty much like it:
var hiTriggers = ['hi', 'hello', 'yo'];
// here goes the receiving message function and what not, then:
for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my English isn't awesome, ikr)
Thanks in advance. If I wasn't clear enough on something, please let me know and I'll edit/formulate it in another way! :)
You can extend prototype:
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
and do:
var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);
Or if you don't want to extend the string object:
foo.substr(i).search(/hi\b/);
both examples where taken from the top answers of Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my > English isn't awesome, ikr)
Actually, regex is for any old pattern matching. It's absolutely useful for this.
fmsf's answer should work for what you're trying to do, however, in general extending native objects prototypes is frowned upon afik. You can easily break libraries by doing so. I'd avoid it when possible. In this case you could use his regexIndexOf function by itself or in concert with something like:
//takes a word and searches for it using regexIndexOf
function regexIndexWord(word){
return regexIndexOf("/"+word+"\b/");
}
Which would let you search based on your array of words without having to add the special symbols to each one.

Why this code doesn't alert the browser type?

Can you tell me what I am missing in writing this code?
<button onclick="getBrowserName()">You Browser Name?</button>
<script>
function getBrowserName()
{
//Uses external interface to reach out to browser and grab browser useragent info.
var browserAgent:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
//Determines brand of browser using a find index. If not found indexOf returns (-1).
if(browserAgent != null && browserAgent.indexOf("Firefox")>= 0)
{
alert("Firefox");
}
else if(browserAgent != null && browserAgent.indexOf("Safari")>= 0)
{
alert("Safari");
}
else if(browserAgent != null && browserAgent.indexOf("MSIE")>= 0)
{
alert("IE");
}
else if(browserAgent != null && browserAgent.indexOf("Opera")>= 0)
{
alert("Opera");
}
else
{
alert("Undefined");
}
return 0;
}
</script>
Well, there are a few things wrong here.
var browserAgent: String: it appears that you're using actionscript syntax, but JS uses dynamic typing, so var is all you need. There's no need to explicitly define the variable's data type, and if you try to do it this way in JS, it's going to give you syntax errors.
ExternalInterface.call: this is another carryover from ActionScript: you don't need this. In fact, it won't work at all because there's no ExternalInterface class in standard JS.
Your getBrowser() function is unnecessary. You're setting browserAgent equal to the result of calling a function from an ExternalInterface, but you can do this directly: var browserAgent = window.navigator.userAgent.
When I fixed those things, it worked fine.
Next time, I would recommend checking the browser console, because, if nothing is happening, the errors that appear there will help you solve your issue nine times out of ten.
Demo
If you replace this line
var browserAgent:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
with this line:
var browserAgent = window.navigator.userAgent;
Then your script works fine on my side.
However, the criteria you use to test the engine are not precise. Have a look at this:
http://www.useragentstring.com/pages/useragentstring.php
There are many browsers that will tell you Firefox even if they another brand. But they are based on each other or they use a specific engine that is built in other browsers too.
If I use your script with a Chrome browser, it says "Safari" instead of "undefined".
About the punctuation: I know of only two places in Javascript where to use the double point:
the conditional operator a = b ? c : d;
the attribute - value assignment in object notation: { name : value }
Your code line containing :String = ExternalInterface... reminds me rather on ActionScript (?).
Im not quite sure what the follow code should be doing. Are you sure its correct?
var browserAgent:String =
ExternalInterface.call("function getBrowser(){return navigator.userAgent;}");
I would expect this code to simply look like this:
var browserAgent = navigator.userAgent;
Below is a example with this change.
http://jsbin.com/lukasere/1/edit

Optional character in input mask

How do I specify an optional character in an input mask?
I found this masked input plugin http://digitalbush.com/projects/masked-input-plugin/ and these mask definitions.
$.mask.definitions['g']="[ ]";
$.mask.definitions['h']="[aApP]";
$.mask.definitions['i']="[mM]";
$.mask.definitions['2']="[0-1]";
$.mask.definitions['6']="[0-5]";
new_mask = "29:69";
$("#txtTime").mask(new_mask);
This defines an input mask for a 12 hour time format, e.g. 11:00. I'd like to allow the user to specify only one digit for the "hour". Instead of having to type 01:00, the user should be able to type 1:00. How do I do that?
You need to use ? for optional characters so in your case you should use "2?9:69".
Quote and example from the page you linked to in your question:
You can have part of your mask be optional. Anything listed after '?'
within the mask is considered optional user input. The common example
for this is phone number + optional extension.
jQuery(function($){
$("#phone").mask("(999) 999-9999? x99999");
});
You can use $.mask.definitions['g']="[0-9 ]";
I have a similar problem I am trying to solve for variable currency amounts ($0.00 - $10000.00), and I don't really understand how the plugin is working.
On the one hand, the $.mask.definitions['symbol'] = '???' bit looks like it's employing a regex fragment, based on the examples in the API reference, and somewhat confirmed by this part in the source, within the mask function's code:
$.each(mask.split(""), function (i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if (firstNonMaskPos == null)
firstNonMaskPos = tests.length - 1;
} else {
tests.push(null);
}
});
...On the other, a mask definition of []|[0-9] does not work (I am attempting to do empty string or 0-9, for those not literate in regex.) For reference, I am attempting to build a mask to fulfill the 0.00-10000.00 condition like oooo9.99, where o is []|[0-9].
Since the code confirms that this is based upon regexes, the null or range pattern should be working but aren't; this is a more obscure bug in the mask framework. Unless I am the one trying to do something incorrectly, which is also possible...

Categories