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

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;
}
}

Related

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

Why does my function not return the error string?

I have function below. It does what it needs to except that it does not return the error string I want.
It always returns "".
I've put breakpoints and seen it step into each error case, but it doesn't return there. It returns at the end of the function.
I'm lost, I'm sure I'm making a really stupid mistake but I don't get it...
Save me the few hairs I have please :)
public validatePanel = () => {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
return "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
return "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
return "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
return "Please select a value for your filter";
}
});
}
});
return "";
}
As pointed out by Alex Bykov, your forEach function is not causing a return.
Your question on why not, per the MDN
The return value of the function is undefined
Return
value undefined.
Which means nothing you can do will generate a return value you can use. Also per the MDN there is no way to stop or break the loop other than throwing an exception.
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool, use a plain loop instead. If you are testing the
array elements for a predicate and need a Boolean return value, you
can use every() or some() instead. If available, the new methods
find() or findIndex() can be used for early termination upon true
predicates as well.
Which means you will need to throw your exception in the forEach loop and then catch the exception and return the string like below
(unless you use a normal for loop then you can do whatever you please)
try {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
throw "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
throw "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
throw "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
throw "Please select a value for your filter";
}
});
}
});
}
catch(err) {
console.log(error);
}

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;

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