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 () { ... }).
Related
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;
}
}
This is my code:
$('.btn-back').off('click').on('click', function (event) {
var valid = carInfo.validate();
if (valid) {
event.preventDefault();
}
});
the sentence event.preventDefault() always executes no matter what value valid is.
When I change the code to
$('.btn-back').off('click').on('click', function (event) {
var valid = carInfo.validate();
if (valid) {
event.preventDefault();
} else {
}
});
it runs the way it should be. Maybe it's something related to Automatic Semicolon Insertion (ASI).
Use the jQuery Validation plugin way:
carInfo.validate() will return Validator object.
So valid variable is always true. Use valid method from docs:
$('.btn-back').off('click').on('click', function (event) {
carInfo.validate();
if (carInfo.valid()) {
event.preventDefault();
}
});
I want to write a assert() function in Js. Something like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
return return;
}
}
But it's not true.
We can write it like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
return true
} else {
return false;
}
}
And use that like this:
function () {
if(!assert(condition)) { return; }
//Other Lines
}
But it could be better if we were be able to use that like this:
assert(condition, 'OK');
Is it possible to return a return?
In fact have we any way to use something like to previous line to end a function by a assert?
Update:
My goal is end a function by a simple assert(condition) use, and not
with use second conditions like if(!assert(condition)) { return; }.
p.s: I'm a newbie.
How about throwing an exception from assert if not true and otherwise nothing. That way, you can use them as you might be familiar already from other languages.
Code example:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
throw "Assertion failed!";
}
}
It seems to me you just want to write less code. If you want to write lots of asserts then consider having a function that processes your list for you, then you only need to maintain an array of parameters:
var list = [
[condition, 'OK'],
[condition2, 'OK'],
[condition3, 'OK'],
[condition4, 'OK']
];
function runAsserts(asserts){
for(var i = 0; i < asserts.length; i++){
if(!assert(asserts[i][0], asserts[i][1])) {
return;
}
}
}
Then you just call it with:
runAsserts(list);
The following code sample (also at http://jsfiddle.net/MZwBS/)
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}
});
document.write(items[0].example);
produces
'function () { if (0 > 1) { return "true"; } else { return "false"; } }'
instead of
'false'
It seems like I've been able something like this with ExtJS. Can anyone tell me where I went wrong? I'd like to evaluate anonymous functions like this on-the-fly.
Do you mean to execute it?
document.write(items[0].example());
You want:
document.write(items[0].example());
When you skip the parentheses, you are saying, "Print this function." When you have them, you are saying, "Evaluate this function and print the result."
I've solved my issue by adding '()' after the anonymous function as shown below. http://jsfiddle.net/MZwBS/7/
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}()
});
document.write(items[0].example);
This code block now produces the expected result of
'false'
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;
}