How to combine two if statements into one? - javascript

I know there is a much cleanlier way to write this than multiple if statements but when I try to combine them my validation stops working! This isn't good practice right? Or in this case is two different if statements okay?
My code:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
}
var x = document.forms["contestForm"]["lastName"].value;
if (x == null || x == "") {
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#lastNamespan'), 'formError');
}
return success;
}
My attempt to combine:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName", "lastName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan', '#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan', '#lastNamespan'), 'formError');
}
return success;
}
So what am I doing wrong? I also will need to add a birthday and e-mail validation but I wanted to get this cleaned up first before it became a monster of if else statements! Sorry for the extra non-helpful information its making me write more because I have to much code. Please feel free to edit and delete this once its posted.

Combine them by functional programming:
function validateForm() {
var x = document.forms["contestForm"]["firstName"].value;
//calls the function checkObject with the object x and the id
var success1 = checkObject(x, '#firstNamespan');
//the result of success1 is either true or false.
var x = document.forms["contestForm"]["lastName"].value;
//calls the function checkObject with the object x and the id
var success2 = checkObject(x, '#lastNamespan');
//the result of success2 is either true or false.
//returns true if both success1 and success2 are true, otherwise returns false.
return success1 && success2;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Which could then be condensed into
function validateForm() {
return checkObject($('form[name="frmSave"] #firstName').val(), '#firstNamespan') && checkObject($('form[name="frmSave"] #lastName').val(), '#lastNamespan');
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Answer for N number of fields with your pattern of naming
function validateForm() {
var itemsToValidate = ["#firstName", "#lastName", "#birthday", "#email"];
var results = [];
$.map( itemsToValidate, function( val, i ) {
results.push(checkObject($('form[name="frmSave"] ' + val).val(), val + 'span'));
});
for(var i=0; i<results.length; i++)
{
if(results[i] == false)
return false;
}
return true;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Note: I didn't validate any of the JavaScript above please call me out if i made a mistake. I just typed this up in notepad as i'm out the door at work

Break things up into functions and utilize an array to loop through the fields to validate.
function isValidField(fieldName) {
var value = document.forms["contestForm"][fieldName].value;
return !(value == null || value == "");
}
function displayFieldError(fieldName) {
addClass($('#' + fieldName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
}
var fields = ['firstName', 'lastName'];
var isValidForm = true;
fields.map(function(fieldName) {
if (!isValidField(fieldName)) {
displayFieldError(fieldName);
isValidForm = false;
}
});
if (isValidForm) {
// Form is correct, do something.
}

By giving them a seperate identifier like this
var x = document.forms["contestForm"]["firstName"].value;
var y = document.forms["contestForm"]["lastName"].value;
if ((x == null || x == "") && (y == null || y == "")) {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
removeClass($('#lastNamespan'), 'formError');
}
But you need to be more precise about, what would you do with just addClass? That won't work. You need have a JS object before this method call.
I think, you want some element there before the addClass and removeClass. Or they need to be like this
$('#firstNamespan').removeClass('formError');
Like this, you need to change your code. So that the object comes first and then the method call.

Make it a function,
function validateForm(formName) {
var x = document.forms["contestForm"][formName].value;
if (x == null || x == "") {
addClass($('#' + formName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
}
removeClass($('#' + formName + 'span'), 'formError');
addClass($('.validationError'), 'is-hidden');
return true;
}
then you can call it twice,
function validateForm() {
var success = validateForm('firstName');
if (success) {
success = validateForm('lastName');
}
return success;
}

The two ifs are checking two different form elements, and showing and hiding two different validation error elements.
Combining them will not be just a code refactor but also change functionality.
The only thing they have in common are that they both use the same variable 'x'.

Related

exporting function return value

I have a code below
function createRoom(){
$(document).keyup(function(event) {
if ($("#room_name").is(":focus") && event.key == "Enter") {
var plainText = document.querySelector(".create-room-class").value;
var createRoomName = plainText.replace(/(<([^>]+)>)/gi, "");
createRoomName = createRoomName.replace(/ +/g, "");
createRoomName = createRoomName.trim();
if(createRoomName.length == 0){
alert("empty");
} else if(createRoomName.length < 5){
alert("Room name must be equal or longer than 5 characters");
} else if(!createRoomName.length == 0)
{
getCreatedRoomName(createRoomName);
window.location = createRoomName;
}
}
});
}
createRoom();
function getCreatedRoomName(x){
return x;
}
What it does is first checks if input field is not empty and if not smaller than 5 characters. If everything is fine then we pass that value to a function and then redirect to that created name url. Look below.
getCreatedRoomName(createRoomName);
window.location = createRoomName;
And we return value (return x)
function getCreatedRoomName(x){
return x;
}
How can I retrieve that returned value in nodejs? I tried modules it doesn't work for some reason.

Assign a standard jQuery function to a variable

How can I assign these functions submit() and click() to a variable. So that I can use them in an if statement like this:
function sendToCheckout() {
$(document).ajaxComplete(function(){
if($("form[action='/cart']").length == 1){
var x = submit();
}
else {
var x = click();
}
$("form[action='/cart']").off().x(function(event){
event.preventDefault(event);
var amountToSend = sessionStorage.getItem('amountToSend');
if(amountToSend != null && amountToSend != "0"){
sendData();
}
else{
window.location.href = shopAddress + "/checkout";
}
});
});
}
With the above code I got the error Uncaught ReferenceError: submit is not defined
These functions are also the names of events, so you can work with them that way.
Assign the event name as a string, then use .on(), which takes the event name as a parameter.
You also shouldn't have multiple var x declarations. Declare it before the if, then assign it in it.
function sendToCheckout() {
$(document).ajaxComplete(function() {
var x;
if ($("form[action='/cart']").length == 1) {
x = "submit";
} else {
x = "click";
}
$("form[action='/cart']").off().on(x, function(event) {
event.preventDefault(event);
var amountToSend = sessionStorage.getItem('amountToSend');
if (amountToSend != null && amountToSend != "0") {
sendData();
} else {
window.location.href = shopAddress + "/checkout";
}
});
});
}

Having a main function call smaller functions?

I've got three separate functions for my javascript:
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
How do I call these separate functions into one main function? I'm not very good with Javascript, so I'm pretty stumped :|
If I understand correctly (let me know if I don't), it looks like you want to create a function that calls each of these individual functions and returns true only if all three validations succeed.
To do that, you'd simply use the && operator like this:
function validate() {
return validateAge() && validateName() && validateEmail();
}
This function will tell you if the age is valid AND the name is valid AND the email is valid.
For this to work, as nnnnnn pointed out, you'd have to return true in the last line of your validateName function; otherwise it would return undefined when the validation succeeds.
Just make a new function and this call others
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
function globalFunction() {
validateAge();
validateName();
validateEmail();
}
</script>
In this example, you need call a "globalFunction();"
Bye

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

Categories

Resources