Exit the javascript code when the validation failed - javascript

I need help to exit the JavaScript code when the validation failed. At the moment I am having the right error message when the validation failed but the JavaScript code continue running. Please find my code below. Thanks
var CompPlanID=1;
var Component=2;
var TierNo=3;
var StartDate=4;
var EndDate=5;
var TierMin=6;
var TierMax=7;
var Rate=8;
var InvalidFlag = 0;
var BlankTextBox = '';
function DateCheck()
{
var StartDateform= document.getElementById('tblTarget').rows[1].cells[StartDate].getElementsByTagName('input')[0].value;
var EndDateform= document.getElementById('tblTarget').rows[1].cells[EndDate].getElementsByTagName('input')[0].value;
var eDate = new Date(EndDateform);
var sDate = new Date(StartDateform);
if(StartDateform== BlankTextBox || EndDateform == BlankTextBox || sDate> eDate)
{
alert("Please ensure that the End Date is greater than or equal to the Start Date.");
InvalidFlag = 1;
}
}
// Check if the pk row is not empty
function CheckPkRow()
{
var CompPlanIDform= document.getElementById('tblTarget').rows[1].cells[CompPlanID].getElementsByTagName('select')[0].value;
if(CompPlanIDform== BlankTextBox)
{
alert("Please ensure that the primary key is not empty");
InvalidFlag = 1;
}
}
function Submit()
{
InvalidFlag = 0;
CheckPkRow();
DateCheck();
//Call the submit function if the validation is true.
if(InvalidFlag == 0 )
{
$('button_submit').click();
alert('The new rate submitted');
}
}

function CheckPkRow()
{
var CompPlanIDform= document.getElementById('tblTarget').rows[1].cells[CompPlanID].getElementsByTagName('select')[0].value;
if(CompPlanIDform== BlankTextBox)
{
alert("Please ensure that the primary key is not empty");
InvalidFlag = 1;
return false;
}
}

Change your code as
function DateCheck()
{
var StartDateform= document.getElementById('tblTarget').rows[1].cells[StartDate].getElementsByTagName('input')[0].value;
var EndDateform= document.getElementById('tblTarget').rows[1].cells[EndDate].getElementsByTagName('input')[0].value;
var eDate = new Date(EndDateform);
var sDate = new Date(StartDateform);
if(StartDateform== BlankTextBox || EndDateform == BlankTextBox || sDate> eDate)
{
alert("Please ensure that the End Date is greater than or equal to the Start Date.");
return false;
}
return true;
}
function CheckPkRow()
{
var CompPlanIDform= document.getElementById('tblTarget').rows[1].cells[CompPlanID].getElementsByTagName('select')[0].value;
if(CompPlanIDform== BlankTextBox)
{
alert("Please ensure that the primary key is not empty");
return false;
}
return true;
}
function Submit()
{
if(CheckPkRow() && DateCheck())
{
$('button_submit').click();
alert('The new rate submitted');
}
}

Related

Google Scripts - Using a drop-down menu to show a balance

So I have used data validation to create a drop-down menu that will then update some cells to show the budget amount that is remaining from another sheet. Nothing is occurring when I try to update the field.
The first check for if a checkbox is marked true all works, so I know it is entering the first if. I just can't seem to get it to enter the second if.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var day = entry.getRange("B9").getValue();
var month = entry.getRange("B10").getValue();
var total = entry.getRange("B11").getValue();
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
//var daysRemaining = DATEIF(today, summary.getRange("D4"), "D");cell functions not allow
//var monthsRemaining = DATEIF(today, summary.getRange("D4"), "M");cell functions not allowed
console.log("Entered 2nd if")
if (e.value == summary.getRange("B59").getValue) {
var balance = summary.getRange("E59").getValue
console.log("Entered 3rd if")
}
else if (e.value == summary.getRange("B60").getValue()) {
var balance = summary.getRange("E60").getValue()
}
else if (e.value == summary.getRange("B61").getValue()) {
var balance = summary.getRange("E61").getValue()
}
else if (e.value == summary.getRange("B62").getValue()) {
var balance = summary.getRange("E62").getValue()
}
else if (e.value == summary.getRange("B63").getValue()) {
var balance = summary.getRange("E63").getValue()
}
else if (e.value == summary.getRange("B64").getValue()) {
var balance = summary.getRange("E64").getValue()
}
else if (e.value == summary.getRange("B65").getValue()) {
var balance = summary.getRange("E65").getValue()
}
else if (e.value == summary.getRange("B66").getValue()) {
var balance = summary.getRange("E66").getValue()
}
else if (e.value == summary.getRange("B67").getValue()) {
var balance = summary.getRange("E67").getValue()
}
else if (e.value == summary.getRange("B68").getValue()) {
var balance = summary.getRange("E68").getValue()
}
else if (e.value == summary.getRange("B69").getValue()) {
var balance = summary.getRange("E69").getValue()
}
else if (e.value == summary.getRange("B70").getValue()) {
var balance = summary.getRange("E70").getValue()
}
else if (e.value == summary.getRange("B71").getValue()) {
var balance = summary.getRange("E71").getValue()
}
day.setValue(balance / 56);
month.setValue(balance / 2);
total.setValue(balance);
}
}
}
Any thanks would be hugely appreciated!
EDIT 5/8/20
Fixed using Cooper's suggestions
Also here is a copy of the sheet this script is for.
That's better but you still have some problems at the end.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var dA=entry.getRange('B9:B11').getValues();
var day = dA[0][0];
var month = dA[0][1];
var total = dA[0][2];
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
var bvs=summary.getRange('B59:B71').getValues();
var erg=summary.getRange('E59:E71');
var evs=erg.getValues();
for(var i=0;i<bvs.length;i++) {
if(e.value==bvs[i][0]) {
var balance=evs[i][0];
break;
}
}
entry.getRange('B9').setValue(balance/56);
entry.getRange('B10').setValue(balance/2);
entry.getRange('B11').setValue(balance);
//day.setValue(balance / 56);//day is not a range so there is no setValue Method
//month.setValue(balance / 2);//day is not a range so there is no setValue Method
//total.setValue(balance);//day is not a range so there is no setValue Method
}
}
}

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

Could someone explain why my functions are not working?

So I'm very new to JavaScript and I'm trying a very simple enter text and check it. It doesn't seem to work the way I want it to. I want all of the inputs to go through the checkInputs. After All of them are 100% I want it to check if hoursWorked and horlyRate are numbers above 0. It seems to just move on to the checkNumberValidation without checking if all inputs are filled.
I got:
function checkNumbersValidation(field){
if( isNaN(field) ) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
var test = false;
do{
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
}else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}else {
tests = true;
}
}while (test = false)
}
function handelCalcButtonClicked (e) {
var passFirstTests = false;
var textFields = ["fullName", "hoursWorked", "hourlyRate"];
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
checkInputs(field);
}
if( **something** ) {
var numberFields = ["hoursWorked", "hourlyRate"]
for ( var i = 0; i < numberFields.length; i++ ) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
clearly I don't know what I'm doing. In the function handelCalcButtonClicked I'm not sure how to move on the the next part (the part Saying something). Any help would be nice!
Inside checkNumbersValidation you need to do the isNan call on field.value, not field:
if( isNaN(field.value) )
If you want to know if all of your fields have gone through checkInputs and have passed, you will need checkInputs to return whether or not each field has passed:
function checkInputs(field) {
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
return false;
} else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return false;
}
return true;
}
This will allow you to know if all fields have passed the check:
var passedAllChecks = true;
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
passedAllChecks = checkInputs(field) && passedAllChecks;
}
if(passedAllChecks) {
/* do number validation stuff */
}
What about this:
function checkNumbersValidation(field) {
if (isNaN(field)) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
return;
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
var textFields = ["fullName", "hoursWorked", "hourlyRate"],
numberFields = [ "hoursWorked", "hourlyRate"],
i,
field;
for (i = 0; i < textFields.length; i++) {
field = document.getElementById(textFields[i]);
checkInputs(field);
}
for (i = 0; i < numberFields.length; i++) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
or:
function checkInput(field, isnumber) {
if (!field) return;
if (isnumber === true && isNaN(field)) {
field.value = "Must be a number";
field.focus("");
return;
}
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return;
}
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
checkInput(document.getElementById('fullName');
checkInput(document.getElementById('hoursWorked', true);
checkInput(document.getElementById('hourlyRate', true);
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});

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

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources