Javascript If else statement trouble within a Function Validate() - javascript

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

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

If condition not working if (str == "1") while data is returning 1

If condition not working while data is returning 1 and 0 but it always execute the else code, i am unable to find error, code is working fine on localhot but not on server
$('#by_head_name').on('blur', function() {
var headsubt = document.getElementById('by_head_name').value;
if (headsubt !== "") {
//alert('hi');
$.post('verify-head-or-subhead-name.php', {
headsub: headsubt
},
function(data, status) {
var str = data;
if (str == "1") {
var headd = "ok";
alert('ok');
} else if (str == "0") {
alert("No Head Exist, Please choose valid Head or create one before selecting it");
} else {
alert(data);
this.value == '';
}
});
}
Please check what "data" of the success function returns in your alert message.
If it returns string directly, then your condition should work.
If it shows object in the alert screen, please verify your object and accordingly choose a variable which satisfy your condition like data.value.

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.

Form submits despite of javascript validation returning false and displaying alert message

I have a form to be filled in by the users, and empty fields would prompt JavaScript validation to return a message to fill in that specific field. I'm able to accomplish this all except that in spite of returning an "Alert" message, the form gets submitted. How do I avoid this? Here's my JavaScript:
function validateHandAppr(theForm) {
// Recom or Not Recom
if (document.project.rec.selectedIndex == 0) {
alert("Please Choose the Recommendation Priority .");
project.rec.focus();
return false;
}
// Recommended priorities
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value == "") {
alert("Fill in the date when culture was received.");
project.recvd_dt.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_by.value == "") {
alert("Specify who received the culture.");
project.recvd_by.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value != "") {
var validformat = /^\d{4}\-\d{2}\-\d{2}$/; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value)) {
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
} else { //Detailed check for valid date ranges
var yearfield = project.recvd_dt.value.split("-")[0]
var monthfield = project.recvd_dt.value.split("-")[1]
var dayfield = project.recvd_dt.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield - 1, dayfield)
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
return false;
} else {
return true;
}
}
}
}
Following is the form where JavaScript is being called:
<form accept-charset="UTF-8" id="project" name="project"
action="hand_submit_forms.php" method="post"
onSubmit="return validateHandAppr(this)"
class="user-info-from-cookie" enctype="multipart/form-data">
Following is the updated code,as per suggested by DaveRandom:
function validateHandAppr(theForm) {
// Recom or Not Recom
//var val=true;
if ( document.project.rec.selectedIndex == 0 )
{
alert ( "Please Choose the Recommendation Priority ." );
document.project.rec.focus();
return false;
}
// Recommended priorities
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value == "")
{
alert("Fill in the date when culture was received.");
document.project.recvd_dt.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_by.value == "")
{
alert("Specify who received the culture.");
document.project.recvd_by.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value != ""){
var validformat=/^\d{4}\-\d{2}\-\d{2}$/ ; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value))
{
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
}
else{ //Detailed check for valid date ranges
var yearfield=project.recvd_dt.value.split("-")[0]
var monthfield=project.recvd_dt.value.split("-")[1]
var dayfield=project.recvd_dt.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
{
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
return false;}
else
{
return true; }
}
}
// return val;
}
The problem is these lines:
project.rec.focus();
// ...
project.recvd_dt.focus();
// ...
project.recvd_by.focus();
Your validation conditions reference document.project but the above lines represent simply project - which does not exist globally because it is a child of document, not window and you did not declare it locally.
Because these lines are between the alert() lines and the return false; lines, you will see the alert but the return statement will never be reached - so the function will not return false and the form will be submitted.
If you change the lines to:
document.project.rec.focus();
// ...
document.project.recvd_dt.focus();
// ...
document.project.recvd_by.focus();
...it should work.
However
You should assign the functions to the <form>s DOM object's submit event instead of using inline event handlers.
If you do this, you will be passed an event object to the first argument of the function, and you can use event.preventDefault() instead of returning false. This would avoid the problem (if the line was placed before the error occurred), and is generally a better way to handle this, because returning false also stops propagation of the event, which may not be desired - actually this makes little difference in this specific case but as a general rule it is true.
If you do this, the handler will be executed in the context of the DOM object - so the this variable will be a reference to it, and you won't need to pass it in as an argument.

Categories

Resources