Javascript validate empty fields - javascript

Can anyone help me on how to validate the javascript form if the
following fields are empty? It doesn't seem to work for my code.
function addvalidation(){
var w = document.forms["shop"]["w"].value;
var t = document.forms["shop"]["t"].value;
var a = document.forms["shop"]["a"].value;
var c = document.forms["shop"]["c"].value;
var s = document.forms["shop"]["s"].value;
var c = document.forms["shop"]["c"].value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}
http://jsfiddle.net/tn2fvh4p/91/
http://jsfiddle.net/tn2fvh4p/68/

Please use following code
function addvalidation(){
var w = document.getElementById("w").value;
var t = document.getElementById("t").value;
var a = document.getElementById("a").value;
var c = document.getElementById("c").value;
var s = document.getElementById("s").value;
var c = document.getElementById("c").value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}

Related

HTML Form won't submit after validaiton with Javascript

I have questions regarding form submitting in HTML with Javascript.
My Javascript is as follows:
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
alert("Your name cannot be blank");
}
if (b == null || b == "") {
alert("Enter a valid email address.");
}
if (c == null || c == "") {
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
alert("Must select an Issue.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (g == null || g == "") {
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
alert("Preferred time must follow the format set.");
}
return false;
}
And this is my form with its attributes in HTML:
<form name="myForm" onsubmit="return validateForm()" method="post" action="confirm.html" novalidate="novalidate" >
What happens is that when I click the Submit button after filling in all the requirements(so everything does not return false) , the form won't submit itself.
After reading around regarding return false, I tried adding else{ return true; } but all it does is submit my form without validation at all.
What do I do to make it work with only Javascript and/or HTML? Thank you!
At the end of the submission function, you are returning:
return false;
}
No matter if the validation was successful or not. This prevents the form from submitting. Make sure you are using return true here and correctly validate using a flag and then if the flag is true, return false.
You have already a flag isValid. Replace the above line with:
return isValid;
}
You need to check if your inputs have passed your tests.
You can do that by using your var isValid.
All you need to do is set isValid to false if one of your conditions was not met, and then return isValid.
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
isValid=false;
alert("Your name cannot be blank");
}
if (b == null || b == "") {
isValid=false;
alert("Enter a valid email address.");
}
if (c == null || c == "") {
isValid=false;
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
isValid=false;
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
isValid=false;
alert("Must select an Issue.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (g == null || g == "") {
isValid=false;
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
isValid=false;
alert("Preferred time must follow the format set.");
}
return isValid;
}

Javascript: Where do i add the redirection?

I just need my form to redirect the user to another page after validation using javascript.
Here is my code:
function checkEnq() {
var x = document.forms["enq"]["email"].value;
var y = document.forms["enq"]["dB"].value;
var z = document.forms["enq"]["textF"].value;
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
}
}
How do i add the location.href or window.open once the js has checked that all fields (email, dB,& textF) are filled?
i can add target="_blank" action="./result.html" to the <form> field and it will still redirect to the result page even if the form is not filled up completely.
Add a "else" block
function checkEnq() {
var x = null;
var y = null;
var z = null;
try {
x = document.forms["enq"]["email"].value;
y = document.forms["enq"]["dB"].value;
z = document.forms["enq"]["textF"].value;
} catch(e) {
alert('code error');
};
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
} else {
document.location.href="/redirect.page"
}
}
I solved it by using this window.open("./page.html") instead of document.location.href

Php echo of json_encode returns value but null in javascript(ajax)

I have a registration form which i would like to get the last id from the php for java to be used inside window.location. I'm using json_encode to encode the value from php to javascript. Before the page redirects i can see the echoed json_encode with the last id but the id variable used inside window.location returns null.
Any help would really be appreciated. Please forgive any amateur mistakes since I'm not a javascript(ajax expert).
<?php
if(isset($_POST['n'])){
$user = new User();
$user->name = trim($_POST['n']);
$user->email = trim($_POST['e']);
$user->password = trim($_POST['p']);
$user->name_of_institution = trim($_POST['ni']);
$user->name_of_institution_db = strtolower(str_replace(" ", "_", (trim($_POST['ni']))));
$user->type_of_school = trim($_POST['st']);
$user->country = trim($_POST['c']);
$user->region = trim($_POST['r']);
$user->town = trim($_POST['t']);
$user->zip_code = trim($_POST['z']);
$user->postal_address = trim($_POST['pa']);
$user->street_address = trim($_POST['sa']);
$user->school_code = trim($_POST['sc']);
$user->waec_code = trim($_POST['wc']);
$user->doe = trim($_POST['d']);
$user->registration_date = strftime("%Y-%m-%d %H:%M:%S", time());
$user->uid = crypt(uniqid(rand(),1));
//ERROR HANDLING
if($user->name == "" || $user->email == "" || $user->password == "" || $user->name_of_institution == "" || $user->type_of_school == "" || $user->country == "" || $user->region == "" || $user->town == "" || $user->zip_code == "" || $user->postal_address == "" || $user->street_address == ""|| $user->school_code == "" || $user->waec_code == "" || $user->doe == "" ){
echo "The submission form is missing some values. Kindly complete the form and try again";
exit();
} else {
if($user->save() && $user->create_school_table() && $user->create_comment_table() && $user->create_course_table() && $user->create_teacher_table() && $user->create_score_table() && $user->create_status_table() && $user->create_message_table() && $user->create_reply_table() && $user->create_level_table() && $user->insert_subjects_into_course_table() && $user->insert_levels_into_level_table() && $user->create_timeline_table()) {
//coment saved
//No message needed; seeing the comment again is proof enough
//Important! You could jsut let the page render from here
//But then if the page is reloaded, the form will try
//to resubmit the comment. So redirect instead:
if (!file_exists(SITE_ROOT .DS. 'public_html' .DS. 'images' .DS. $user->id)) {
mkdir (SITE_ROOT .DS. 'public_html' .DS. 'images' .DS. $user->id, 0777);
}
echo "Signup_Success";
$ide = $user->id;
$id = utf8_encode($ide);
echo json_encode($id);
//echo $id;
exit();
//$session->message("Successful Registration.");
//redirect_to("logo_upload.php?id={$user->id}&name_of_institution={$user->name_of_institution}");
}
}
}
?>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
} else if(elem == "school_code"){
rx = /[^0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var n = _("name").value;
if(n != ""){
_("usernamestatus").innerHTML = 'Checking...';
var ajax = ajaxObj("POST", "ajax_form_check.php", true);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("usernamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("name2check="+n);
}
}
function matchpassword(){
var p1 = _("password").value;
var p2 = _("rpassword").value;
if((p1 != p2) || (p2 != p1)){
_("passwordstatus").innerHTML = '<p class=\"btn btn-danger text-center col-sm-6 col-sm-offset-3\">Confirmation failed. Please recheck.</p>';
}else {
_("passwordstatus").innerHTML = '';
}
}
function signup(){
var n = _("name").value;
var e = _("email").value;
var p1 = _("password").value;
var p2 = _("rpassword").value;
var ni = _("name_of_institution").value;
var st = _("type_of_school").value;
var c = _("country").value;
var r = _("region").value;
var t = _("town").value;
var z = _("zip_code").value;
var pa = _("postal_address").value;
var sa = _("street_address").value;
var sc = _("school_code").value;
var wc = _("waec_code").value;
var d = _("doe").value;
var status = _("status");
if(n == "" || e == "" || p1 == "" || p2 == "" || ni == "" || st == "" || c == "" || r == "" || t == "" || z == "" || pa == "" || sa == ""|| sc == "" || wc == "" || d == ""){
window.scrollTo(0,0);
status.innerHTML = "<p class=\"btn btn-danger text-center col-sm-6 col-sm-offset-3\">Please complete the form. There seems to be some empty spaces. Thank you.</p><br>";
} else if(p1 != p2){
window.scrollTo(0,0);
status.innerHTML = "<p class=\"btn btn-danger text-center col-sm-6 col-sm-offset-3\">Your password fields do not match</p><br>";
//} else if( _("terms").style.display == "none"){
//status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'Please wait ...';
var ajax = ajaxObj("POST", "regform.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//var id = <?php echo json_encode($id); ?>;
if(ajax.responseText == "Signup_Success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
//var id = <?php echo json_encode($id); ?>;
var id = JSON.parse( '<?php echo json_encode($id); ?>' );
window.location ="logo_upload.php?id="+id+"&name_of_institution="+ni;
}
}
}
ajax.send("n="+n+"&e="+e+"&p="+p1+"&ni="+ni+"&st="+st+"&c="+c+"&r="+r+"&t="+t+"&z="+z+"&pa="+pa+"&sa="+sa+"&sc="+sc+"&wc="+wc+"&d="+d);
}
}
</script>
The php and ajax code are all on the same page regform.php. Will seperating the codes help?

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

how can I correct this JavaScript adding function?

I have a form which takes six inputs (there are more but only these matter for now)
original fare
original tax
new fare
new tax
fee
number of guests
when "Calculate" is pressed I use javascript to add original fare
and original tax to get the original total
then I add new fare and new tax to get the new total
now I compare original total to new total
if original total is greater than new total it should use one if several methods to finish doing the math I need and set the results to the display
i was originally testing everything using these values:
original fare = 1000
original tax = 200
new fare = 800
new tax = 200
fee = 150
number of guests = 3
which can bee seen here https://pnrbuilder.com/_popups/exchangeMyPNR_MATH_TEST_2.php
(page only works in chrome)
the above works exactly as expected but when I change the values to:
original fare = 949.83
original tax = 321.18
new fare = 453.91
new tax = 143.91
fee = 150
number of guests = 3
seen here https://pnrbuilder.com/_popups/exchangeMyPNR_MATH_TEST.php
(page only works in chrome)
this test uses the wrong if statement to finish out the rest of the math
I dont understand why this is happening as original total is still > new total so it should use the same method as the first example. I put in alerts to let me know exactly which if statement is being used to do the math and clearly the wrong one is used here but I just cant figure out why.
I know this is convoluted but could someone please help me figure out where my logic goes wrong?
Here's the full function:
function addMe(frm) {
var orBase = Number(frm.box1.value);
var orTax = Number(frm.box2.value);
var nwBase = Number(frm.box3.value);
var nwTax = Number(frm.box4.value);
var fee = Number(frm.fee.value);
var gsts = Number(frm.guests.value);
var fltrd_orBase = orBase * 100;
var fltrd_orTax = orTax * 100;
var fltrd_orTtl = fltrd_orBase + fltrd_orTax;
var orTtl = fltrd_orTtl / 100;
var final_orTtl = orTtl.toFixed(2)
frm.result.value = orTtl.toFixed(2)
var fltrd_nwBase = nwBase * 100;
var fltrd_nwTax = nwTax * 100;
var fltrd_nwTtl = fltrd_nwBase + fltrd_nwTax;
var nwTtl = fltrd_nwTtl / 100;
var final_nwTtl = nwTtl.toFixed(2)
frm.result2.value = nwTtl.toFixed(2)
var e = document.getElementById("residual");
var selectVal = e.options[e.selectedIndex].value;
if (final_orTtl <= final_nwTtl) {
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="none";
var undiff = final_nwTtl - final_orTtl;
var diff =undiff
document.getElementById("differenceDisplay").innerHTML=diff.toFixed(2);
frm.difference.value = diff.toFixed(2);
var ppCost = diff + fee;
frm.pptotal.value = ppCost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=ppCost.toFixed(2);
var ttlCost = ppCost * gsts;
frm.totalcost.value = ttlCost.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlCost.toFixed(2);
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 1 was used');
}
}
else if (final_orTtl > final_nwTtl) {
if (selectVal == "residualX" || selectVal == "residualN") {
document.getElementById("MCOtable").style.display="none";
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = displayDiff.toFixed(2);
document.getElementById("forfeitInfo").innerHTML = "Beyond the cost above";
frm.lost.value = diff.toFixed(2);
document.getElementById("ppForfeitedDisplay").innerHTML = diff.toFixed(2);
var ttlfForfeited = diff * gsts;
frm.lostTTL.value = ttlfForfeited.toFixed(2);
document.getElementById("totalForfeitedDisplay").innerHTML=ttlfForfeited.toFixed(2);
var ppCost = fee;
frm.pptotal.value = ppCost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=ppCost;
var ttlCost = fee * gsts;
frm.totalcost.value = ttlCost.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlCost;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.1 was used');
}
}
// this is the method that should be used below
else if (selectVal == "residualA" ) {
document.getElementById("MCOtable").style.display="none";
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = diff.toFixed(2);
if ( diff > fee) {
var residual = diff - fee ;
document.getElementById("forfeitInfo").innerHTML = "No additional cost. However,";
frm.lost.value = residual.toFixed(2);
document.getElementById("ppForfeitedDisplay").innerHTML = residual.toFixed(2);
var ttlfForfeited = residual * gsts;
frm.lostTTL.value = ttlfForfeited.toFixed(2);
document.getElementById("totalForfeitedDisplay").innerHTML=ttlfForfeited.toFixed(2);
//document.getElementById("differenceDisplay").innerHTML=0;
frm.difference.value = diff;
document.getElementById("ppDisplay").innerHTML=0;
document.getElementById("grandTotalDisplay").innerHTML=0;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.2 was used');
}
}
else {
var remBal = fee - diff ;
var ttlcost = remBal * gsts;
frm.totalcost.value = ttlcost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=remBal.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlcost.toFixed(2);
document.getElementById("forfeitTable").style.display="none";
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.3 was used');
}
}
}
else if (selectVal == "residualM" ) {
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = displayDiff.toFixed(2);
if (diff > fee) {
var mco = diff - fee ;
document.getElementById("MCOInfo").innerHTML=mco.toFixed(2);
frm.MCOamt.value = mco.toFixed(2);
//document.getElementById("differenceDisplay").innerHTML=diff;
//frm.difference.value = diff* -1;
frm.totalcost.value = 0;
document.getElementById("ppDisplay").innerHTML=0;
document.getElementById("grandTotalDisplay").innerHTML=0;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.4 was used');
}
}
else {
var remBal = fee - diff ;
var ttlcost = remBal * gsts;
frm.totalcost.value = ttlcost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=remBal.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlcost.toFixed(2);
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="none";
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.5 was used');
}
}
}
}
var nwTtl = fltrd_nwTtl / 100;
var final_orTtl = orTtl.toFixed(2)
var orTtl = fltrd_orTtl / 100;
var final_orTtl = orTtl.toFixed(2)
if (final_orTtl > final_nwTtl ) {
}
This part seems to be my problem. the if comparison im doing here doesnt seem to like the '.toFixed(2)' that I did above it for some reason. I changed it to:
var nwTtl = fltrd_nwTtl / 100;
var orTtl = fltrd_orTtl / 100;
if (orTtl > nwTtl ) {
}
Im still testing all the other features but this seems to be working as expected so far. I would still love to know why my use of '.toFixed(2)' causes two numbers that are clearly higher vs lower to evaluate to the opposite. and will accept any answer to that part of this question

Categories

Resources