How can I pass a Regular Expression through a function? - javascript

I want to validate some fields passing a different pattern to a validation function.
send.addEventListener("click", function (event) {
let pattern = /^[A-Za-zÁ-Úá-ú\s]{3,15}$/;
let nameIsVal = regexValidator(pattern);
if (nameIsVal) {
return true;
} else {
event.preventDefault();
return false;
}
});
function regexValidator(pattern) {
if (!pattern.test(this.value)) {
return false;
} else {
return true;
}
}

I am assuming that you are in a class. Make sure that the this keyword points to the correct instance in your event handler, either with the .bind() keyword or with an arrow function.
I would register the handler like this:
send.addEventListener('click', (event) => this.checkRegex(event));
Or if your environment doesn't support arrow functions, this should work as well:
send.addEventListener('click', this.checkRegex.bind(this, event));
Then I would add the methods to the class like this:
checkRegex(event) {
let pattern = /^[A-Za-zÁ-Úá-ú\s]{3,15}$/;
let nameIsVal = this.regexValidator(pattern);
if (nameIsVal) {
return true;
} else {
event.preventDefault();
return false;
}
}
regexValidator(pattern) {
if (!pattern.test(this.value)) {
return false;
} else {
return true;
}
}

Related

Unexpected token

I have the following to check a few form inputs (will be part of a larger validation) but the console shows unexpected token for the first line.
$( document ).ready(function() {
$('.contactcheck').submit(function) {
var abort = false;
$('#name,#make,#model,#year,#email,#contactmeth').each(function() {
if ($(this).val()==='') {
$(this).addClass(' error');
abort = true;
}
})
if (abort) { return false; } else { return true; }
})
});
Anyone able to point me in the direction of what is wrong? Looks valid to me.
You forgot the open parenthesis after function.
Replace:
$('.contactcheck').submit(function) {
With:
$('.contactcheck').submit(function() {
On a separate note you could simplify your code if you do this:
return abort;
Instead of:
if (abort) { return false; } else { return true; }
jQuery's submit expects a function. Function expressions look like this:
function () {}
So change your code to
$('.contactcheck').submit(function () {
It's the same as in $(document).ready(function () { ... }).

Simple Javascript: How to invoke a function based off user prompt;

I've defined some functions, and I want to get user input to invoke those functions. I have the following code, but can't figure out how to invoke the actual function when I'm using a variable. I assumed below code would work..
thanks!
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
} else {
return false;
}
}
var getCommand = function(){
var command = prompt("Please enter a command");
if (!(command in someFunctions)) {
alert('command not recognized');
getCommand();
} else {
command();
}
}
getCommand();
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
}
else {
return false;
}
}
};
var getCommand = function(){
var commandInput = prompt("Please enter a command");
var command = someFunctions[commandInput];
if (!command) {
alert('command not recognized');
getCommand();
}
else {
command();
}
};
getCommand();
The reason your code isn't working is because you're missing the closing } of someFunctions.
var someFunctions = {
play: function() {
if (player.stopped()) {
player.play();
} else {
return false;
}
}
} // here
Your call is fine, you call a "variable" function the same way you do a regular one. The only difference between a "variable" function and an ordinary one is you can call the ordinary one before it's declared (if you're in the same scope at least)

How do I program the output of one function to feed into the input of another?

If I have a function like this:
var danger = 1;
function stepLeft() {
if (danger == 1) {
alert("stop")
} else {
alert("start")
}
}
...how do I make the "alert("stop")" or any other output like that trigger and supply the expression input for something like a switch statement? So I can set off a chain reaction of consequences? Thanks!
You're mixing concerns here. An alert() is a UI action, it doesn't trigger anything in your code. It just does something on the UI. If you want your function to trigger something else in your code, you'd need to invoke that other thing:
function stepLeft() {
if (danger == 1) {
alert("stop")
someOtherFunction();
} else {
alert("start")
yetAnotherFunction();
}
}
Or, if the functionality can change, you can supply a function to stepLeft:
function stepLeft(stopFunction, startFunction) {
if (danger == 1) {
alert("stop")
stopFunction();
} else {
alert("start")
startFunction();
}
}
and call it:
stepLeft(someOtherFunction, yetAnotherFunction);
Or you might have stepLeft return a value, which other functions can use:
function stepLeft() {
if (danger == 1) {
alert("stop")
return "stop";
} else {
alert("start")
return "start";
}
}
and call it:
var actionPerformed = stepLeft();
someOtherFunction(actionPerformed);
This would actually be a good opportunity to de-couple your UI actions from your logic:
function stepLeft() {
if (danger == 1) {
return "stop";
} else {
return "start";
}
}
and:
var actionPerformed = stepLeft();
alert(actionPerformed);
someOtherFunction(actionPerformed);
The point is, there are a lot of ways to structure your code so that the results of one function can be used by another function.

How to access a JavaScript function parameter in another function

I have two different JavaScript functions in same file, like this:
function functionOne(a)
{
if(a)
{
return true;
}
else
{
return false;
}
}
function functionTwo(b)
{
//I want to access if condition parameter a here
}
I want to access functionOne if condition parameter a in functionTwo.
function functionTwo(b)
{
if(functionOne(b))
return true;
else
return false;
}
The following are the two ways....
Option 1:
<script>
var newVar = "";
function functionOne(a)
{
if(a)
{
newVar = true;
return true;
}
else
{
return false;
}
}
function functionTwo(b)
{
//user newVar vairalbe to get the value
//i want to access if condition parameter a here
}
Option 2:
<script>
function functionOne(a)
{
if(a)
{
return a;
}
else
{
return false;
}
}
function functionTwo(b)
{
// call functionOne(a) to get the value;
//i want to access if condition parameter a here
}
</script>

How to call outer function's return from inner function?

I have such code:
function allValid() {
$('input').each(function(index) {
if(something) {
return false;
}
});
return true;
}
which always returns true as return false; affects anonymous inner function. Is there an easy way to call outer function's return?
PS. I am not looking for a workaround, just want to know the answer to original question. If the answer is "not possible" it is fine.
Yeah, store it in a local variable.
function allValid() {
var allGood = true;
$('input').each(function (index) {
if (something) {
allGood = false;
}
});
return allGood;
}
You could also use Array.prototype.some which iterates until finding an element that matches the criteria.
function allValid() {
var inputs = $('input');
if(inputs.toArray().some(function(input){
if(something)
return true;
})) {
return false;
} else {
return true;
}
}
You can also do this with filter:
var anyInvalid = $('input').filter(function(index) {
if (inValidCheck)
return true;
}).length;
This works because 0 is treated as false, but it actually gives you the number of invalid, which you could use this to display "You have 3 invalid entries" or something if you wanted.
If you want to do this efficiently, I think this is the best way:
function allValid() {
elements = $('input')
for (i = 0; i < elements.length; i++) { invalidityCheck(elements[i]) && return false; }
return true;
}
Edit: Although a more JavaScript-y version would probably use exceptions:
function allValid() {
try
$('input').each(function(index)) {
if (something) { throw 'something happened!'; }
});
catch (e) {
if (e == 'something happened!') {
return false;
} else {
throw e;
}
}
return true;
}

Categories