Java script reduction - javascript

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.")
}
.....
.....
.....

Related

error in javascript conditional statement

I am facing an issue in javascript. if key value is true they stop it return true whereas if key value is false they shows Error.
Problem: they don't read the condition number or name value in if body. if key value is true they terminate.
How should i handle this condition? that they should also read the condition number or name value in if body.
can i use else if statement here ?
var key = $('#key').val().trim();
if(key != "" ){
return true; //value is true if value is true they stopped it
}
if(key === ''){
showError(); //this field is required
return false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' )
{
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
how can i do? anyone help me?
Not sure if this is what you wanted. Have a look. The code continues after checking key.
var key = $('#key').val().trim();
if(key === ''){
showError(); //this field is required
let keyStat = false;
}
//if key value is true they don't execute my number or name condition
if ( $('#number').val().trim() === '' || $('#name').val().trim() === '' || keyStat === false) {
if ($('#number').val().trim() === '') {
showError(); //this field is required
}
if ($('#name').val().trim() === '') {
showError(); //this field is required
}
if (!keyStat) {
showError(); //this field is required
}
return false;
}
else{
return true; //always return true
}
when you call return statement your function will exit,only code before the return statement will run
Example:
function bar(){
var key = 12
if(key === 12){
console.log("only code before the return statement will run")
return true; // when you call return your function will exit
}
console.log("this will be terminated")
}
click me

javascript input validation - Unable to validate when all fields are empty

As a new guy in javascript am trying to create a script which is supposed to validate a registration form. Simple things, if 1 field is empty, throw the appropriate message. I succesfully managed it following the tutorials on the internet, it works the way i want it, database doesn't get updated when 1 field is empty.
However there is a problem. When ALL fields are empty the script somehow fails to notice this and proceeds with the registration perfectly.
My script is the following:
function validateForm()
{
var a=document.forms["Registration_Form"]["fname"].value;
var b=document.forms["Registration_Form"]["lname"].value;
var c=document.forms["Registration_Form"]["email"].value;
var d=document.forms["Registration_Form"]["username"].value;
var e=document.forms["Registration_Form"]["password"].value;
if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e==""))
{
alert("All Field must be filled out");
return false;
}
if (a==null || a=="")
{
alert("First name must be filled out");
return false;
}
if (b==null || b=="")
{
alert("Last name must be filled out");
return false;
}
if (c==null || c=="")
{
alert("email adress must be filled out");
return false;
}
if (d==null || d=="")
{
alert("Username must be filled out");
return false;
}
if (e==null || e=="")
{
alert("Password must be filled out");
return false;
}
}
This is drilling through my brain and driving me crazy for hours.
When 1 field is completed and the rest are missing i get the appropriate message for the first missing field and all good, registration is prevented.
But when all are missing, it just doesn't happen, registration is succesfull and enters all blank fields on my database.
I can't understand, it's here, right?
if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e==""))
{
alert("All Field must be filled out");
return false;
}
If fname is empty AND lname is empty AND email is empty AND username is empty AND password is empty, alert and return false.
I don't understand, how can there be a problem in something so simple? What am i missing?
And even if this line didn't existed, shouldn't the script get caught in the remaining if's that have only 1 clause and give the false there?
I would try it like this. You shouldn't need to check them all at once...
function validateForm()
{
var a=document.forms["Registration_Form"]["fname"].value;
var b=document.forms["Registration_Form"]["lname"].value;
var c=document.forms["Registration_Form"]["email"].value;
var d=document.forms["Registration_Form"]["username"].value;
var e=document.forms["Registration_Form"]["password"].value;
try {
if ((a === '') || (a === null)) {
throw new Error('First name must be filled out');
}
if ((b === '') || (b === null)) {
throw new Error('Last name must be filled out');
}
if ((c === '') || (c === null)) {
throw new Error('email adress must be filled out');
}
if ((d === '') || (d === null)) {
throw new Error('Username must be filled out');
}
if ((e === '') || (e === null)) {
throw new Error('Password must be filled out');
}
return true;
}
catch (formError) {
alert(formError.message);
return false;
}
}

Javascript If else statement trouble within a Function Validate()

The following script should validate only certain input fields depending on the selection a user makes in a drop-down box (var problem).
The trouble I'm having is when the if statement runs for problem == 4 (below) and the user has filled in the corresponding cityid field, the alert (Alert#3) for the next if statement (problem == 5) is triggered. I only want Alert#3 to trigger if the user has selected problem == 5 from the drop-down AND has not filled in the model field.
The same trouble happens respectively when if statement runs for problem == 5.
function ValidateSOR()
{
var user = document.SOR.User;
var problem= document.SOR.Problem;
var cityid = document.SOR.CityID;
var errors1 = document.SOR.ErrorCodes1;
var model = document.SOR.Model;
var errors2 = document.SOR.ErrorCodes2;
var software = document.SOR.SoftwareType;
if (user.value == "")
{
window.alert("Please enter your name.");
user.focus();
return false;
}
if (problem.selectedIndex < 1)
{
alert("Alert#1");
problem.focus();
return false;
}
if (problem.selectedIndex == 4)
{
cityid.focus();
}
else if (cityid.value == "")
{
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5)
{
model.focus();
}
else if (model.value == "")
{
alert("Alert#3");
model.focus();
return false;
}
if (problem.selectedIndex == 6)
{
software.focus();
}
else if (software.value == "")
{
alert("Alert#4");
software.focus();
return false;
}
return true;
}
You're not returning from the function when you discover that the problem is #4. Thus, because it is 4, then it's not 5, and so the "else" part of that branch is taken.
edit — OK, let's look at the code:
if (problem.selectedIndex == 4) {
cityid.focus();
}
else if (cityid.value == "") {
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5) {
model.focus();
}
else if (model.value == "") {
alert("Alert#3");
model.focus();
return false;
}
If the index is 4, what happens? This code runs:
cityid.focus();
Then what? The code proceeds to the next if statement:
if (problem.selectedIndex == 5) {
Now, if we just got through noticing that the index was 4, then what are the chances that it will be equal to 5? Zero! Thus, that comparison is guaranteed to be false, so we move to the else part. Apparently, your "model.value" is the empty string, so that if statement succeeds. You get the alert.
I think your problems would be solved by bringing the logic of the code more in line with the logic of your validation process:
if (problem.selectedIndex == 4 || cityid.value == "") {
cityid.focus();
return false;
}
That way, if the index is 4 or if the city ID value is empty, then you'll treat that as an error with the city ID and exit the function. It won't matter what comes after that, because the return leaves the function at that point.
You should restructure each IF like so:
if (problem.selectedIndex == 4 || cityid.value == "")
{
cityid.focus();
return false;
}
if (problem.selectedIndex == 5 || model.value == "")
//and so on
so it returns either way and does not hit the next if statement

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;

returning error in 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()">

Categories

Resources