returning error in javascript - javascript

I have variable deleteboxvalue
var deleteboxvalue = "111111111111111";
if(deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected."); return true;
}
I want to check if 0 is not exist in this I want to return false and alert as "You can't delete all Contact Number." but in both cases if 0 exist in variable in that case also its returning false and giving me alert as "You can't delete all Contact Number."

I want to check if 0 is not exist in this I want to return false
If that's the case then you've got your logic reversed. You are currently returning false if 0 is in the string (i.e. it is found at an index greater than or equal to 0). If you want to return false when 0 is not found in the string, you can do this:
if(deleteboxvalue.indexOf('0') == -1) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected.");
return true;
}
However, I may have completely misunderstood what you're trying to do...

Create a function in JavaScript such as:
function CheckContacts() {
var deleteboxvalue = "111111111111111";
if (deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
} else {
alert("All Zeros are not selected."); return true;
}
}
and
On body onload call that JavaScript method:
<body onload="CheckContacts()">

Related

how to check the return from function

i'm new to programming , i don't understand this line if(!validateform(siteName,siteURL)) ,what happens if function return false , will it enter the if condition ???
if(!validateform(siteName,siteURL))
return false;
// Validate Form
function validateForm(siteName, siteUrl){
if(!siteName || !siteUrl){
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if(!siteUrl.match(regex)){
alert('Please use a valid URL');
return false;
}
return true;
}
If the function returns false it will enter the if condition, but if the function returns true it won't enter the if condition. This is because you are using the not operator (!).
The not operator simply makes a boolean true value into a false value and a false to a true value.
Firstly there is an error in the line you want to know about when you're calling a function remember it is case-sensitive. Your function is defined as validateForm but you are calling it with validateform.
That aside the below snippet is an attempt to explain what the function does during runtime.
in the below snippet
if(!validateForm(siteName,siteURL))
what this line does is it calls the function validateform() and passes the arguments siteName and siteURL . The function performs certain validations on the parameters and depending on the outcome of the validating statements(commented below) it returns true or false. The condition in the if statement !validateForm(siteName,siteURL) checks to see if the output of the function is false (ie return false;). If it is false it will execute the if statement(remember this depends on the parameters passed). You can see the examples in the snippet to see when the statement returns true/false.
function checkURL(siteName, siteUrl) {
if (!validateForm(siteName, siteUrl)) {
console.log("invalid name " + siteName);
console.log("invalid URL " + siteUrl);
return false;
} else {
console.log("Site name is valid " + siteName);
console.log("Site URL is valid " + siteUrl);
}
}
// Validate Form
function validateForm(siteName, siteUrl) {
if (!siteName || !siteUrl) { //validating statement 1
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (!siteUrl.match(regex)) { //validating statement 2
alert('Please use a valid URL');
return false;
}
return true;
}
console.log("URL and name valid");
checkURL("stackoverflow","https://www.stackoverflow.com");
console.log("URL invalid")
checkURL("stackoverflow","stackoverflow");
console.log("Name not defined");
checkURL(undefined,"https://www.stackoverflow.com");
console.log("URL not defined");
checkURL("stackoverflow",undefined);

Java script reduction

I was wondering if there was anyway of simplifying the code below without using jQuery?
Still very inexperienced with JavaScript so any help is much appreciated! Thank you in advance everyone :D
if (name === "") {
document.getElementById("name").focus();
alert("Name must be filled out.");
return false;
} else if (!(/\S/.test(name))) {
document.getElementById("name").focus();
alert("Name cannot be blank.");
return false;
} else if (!(/^([^0-9]*)$/.test(name))) {
document.getElementById("name").focus();
alert("Name cannot contain numbers.");
return false;
} else if (email === "") {
document.getElementById("email").focus();
alert("Please enter your email address.");
return false;
} else if (/^\S+#\S+\.\S+$/.test(email) === false) {
document.getElementById("email").focus();
alert("Please enter a valid email address.");
return false;
} else if (basecamp === "") {
document.getElementById("basecamp").focus();
alert("Please select a base camp.");
return false;
} else if (max == 0) {
document.getElementById("basecamp").focus();
alert("This base camp has run out of slots, please select another base camp.");
return false;
} else if (package === "") {
document.getElementById("package").focus();
alert("Please select a package.");
return false;
} else if (validdate === "") {
document.getElementById("date").focus();
alert("Please select a date.");
return false;
} else if (groupsize === "") {
document.getElementById("groupsize").focus();
alert("Please select a group size.");
return false;
} else if (groupsize <= 0) {
document.getElementById("groupsize").focus();
alert("Please select a postitve number.");
return false;
} else {
updateData();
}
}
You might use an array of conditions, where each subarray (or subobject) contains the condition to test (what's in your if / else if at the moment), the ID to focus if the condition is true, and the message to alert. Then, iterate over it, finding the first truthy condition - if found, alert the associated message, focus the element, and return false. Otherwise, if none of the bad conditions were found, call updateData:
const arr = [
[
name === "",
'name',
"Name must be filled out."
],
[
!(/\S/.test(name)),
'name',
'Name cannot be blank.'
],
[
!(/^([^0-9]*)$/.test(name)),
'name',
'Name cannot contain numbers.'
]
// etc
];
const firstBadCondition = arr.find(([cond]) => cond);
if (firstBadCondition) {
const [, idToFocus, errorMessage] = firstBadCondition;
document.getElementById(idToFocus).focus();
alert(errorMessage);
return false;
} else {
updateData();
}
You can create a function which takes element id name,email... as parameter and a message that need to alert. return false from that function. And you if-else statements just return that function.
Here is a little example.
function sendMsg(elm,msg){
document.getElementById(elm).focus();
alert(msg)
return false;
}
if (name === "") {
return sendMsg('name',"Name must be filled out.")
} else if (!(/\S/.test(name))) {
return sendMsg("name","Name cannot be blank.")
} else if (!(/^([^0-9]*)$/.test(name))) {
return sendMsg('name',"Name cannot contain numbers.")
} else if (email === "") {
return sendMsg('email',"Please enter your email address.")
} else if (/^\S+#\S+\.\S+$/.test(email) === false) {
return sendMsg('email',"Please enter a valid email address.")
}
.....
.....
.....

What to use in replacement of return boolean

i've applied validation to my form through jquery and in that form i've four checkboxes and the user must check one to submit form.
this is the code:
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox' && c[i].checked == true) {
return true;
} else {
error += alert ("You must select atleast one previous benefit provided");
return false
}
}
the problem is that this use return key and if i remove return key it will alert 4 times (same number of checkboxes) and if i let it be there then the if statement which check fields and give error don't work
if(error != "") {
$("#error").html("<strong>Some fields are invalid!</strong>") || error;
return false;
} else {
return true;
}
if i remove return in checkbox validation then everythings work fine but it give alerts four times and if dont remove it then without giving error it submit the form.
alert() doesn't return anything so your error logic doesn't make sense.
Create a collection of checked checkboxes and make sure it has length instead.
var hasChecked = $('#myForm :checkbox:checked').length;
if(!hasChecked){
return false
error = true;
}

Javascript IF blocks get skipped

I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.

jQuery conditions pass through

I made my own form validation just for 2 inputs, one is for Phone number and another one for Email address. and also I have 2 forms in 1 page.
my code is
var email, phone;
if (email address validation passed) {
email = true;
} else {
email = false;
}
if (phone number validation passed) {
phone = true;
} else {
phone = false;
}
if (!(phone && email)) {
return false
} else {
return true
}
as I have two forms on the same page, I'd like to have another snippet for the 2nd form like,
var email2, phone2;
if (email address validation passed) {
email2 = true;
} else {
email2 = false;
}
if (phone number validation passed) {
phone2 = true;
} else {
phone2 = false;
}
if (!(phone2 && email2)) {
return false
} else {
return true
}
the issue I found is that, for getting the form submitted I need to have email, phone, email2, phone2; all equal to true. however, I need to submit in condition if email, phone are true or phone2, email2 are true
Just need someone to check if this is a right logical way to solve my problem?
if (!(phone2 && email2)) {
return false
} else if(!(phone && email )) {
return false
} else return true;
however, I need to submit in condition if email, phone are true or phone2, email2 are true
The way you said it there is the easiest way to code it:
if ((email && phone) || (email2 && phone2)) {
return true;
} else {
return false;
}
And if you are just going to return true or false based on whether a condition is true or false, you can do it in one line like this:
return (email && phone) || (email2 && phone2);
You can check it like
if((phone2 && email2) || (phone && email))
return true;
else
return false;

Categories

Resources