Prevent action if input field data is not right. (js) - javascript

I am stuck here with some issue. There are 3 two entry boxes: for birthday, an amount and an interest rate (%). If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
So the issue is: When I enter an incorrect date, I get a notification. However, the interest is still calculated afterwards. I want to prevent code from being executed with incorrect input.
document.getElementById("button").onclick = loop;
var inputA = document.getElementById("inputA");
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function allFunctions() {
correctBirthday()
sum();
rate();
loop();
}
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
if (inputA.value == '')
{ alert('Please enter a value for input A');
return;
}
}
function correctDate(datum) {
var vorm = /^\d{2}-\d{2}-\d{4}$/;
return vorm.test(datum);
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return;
}
if ( validDate(d) ) {
result.innerHTML = '';
}
}
function rate() {
var r = rentepercentage.value;
if ( correctRate(r) == true ) {
alert("The form of the amount entered is incorrect");
return;
} else {
result.innerHTML = '';
}
}
function correctRate(rente) {
var vorm = /[a-zA-Z]/;
return vorm.test(rente);
}
function sum() {
var s = bedrad.value;
if ( correctSum(s) === true ) {
alert("The form of the amount entered is incorrect");
return;
} else {
result.innerHTML = '';
}
}
function correctSum(som) {
var vorm = /[a-zA-Z]/;
return vorm.test(som);
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputA" value="05-06-1986"><br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
So the issue is: When I enter an incorrect date, I get a notification. However, the interest is still calculated afterwards. I want to prevent code from being executed with incorrect input.

In your allFunctions function:
function allFunctions() {
correctBirthday()
sum();
rate();
loop();
}
If correctBirthday returns undefined, allFunctions does not know that it should stop. You have two main options:
Throw an error if the birthday is incorrect, and catch it later:
function allFunctions() {
try {
correctBirthday()
sum();
rate();
loop();
} catch ( error ) {
alert( error.message );
}
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
throw new Error("The form of the date is incorrect");
}
if ( validDate(d) ) {
result.innerHTML = '';
}
}
Let correctBirthday return true or false depending on whether it succeeded, and let allFunctions respond appropriately:
function allFunctions() {
let birthdayIsCorrect = correctBirthday();
if ( !birthdayIsCorrect ) {
return;
)
sum();
rate();
loop();
}
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return false;
}
if ( validDate(d) ) {
result.innerHTML = '';
}
return true;
}
EDIT: If you want this behaviour when validDate(d) is false as well, try...
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
throw new Error("The form of the date is incorrect");
}
if ( !validDate(d) ) {
throw new Error("The date is invalid");
}
result.innerHTML = '';
}
// or...
function correctBirthday() {
var d = inputA.value;
if ( correctDate(d) == false ) {
alert("The form of the date is incorrect");
return false;
}
if ( !validDate(d) ) {
alert("The date is invalid");
return false;
}
result.innerHTML = '';
return true;
}

Related

how to implement multiple javascript function in onSubmit() form

I have 4 js function:validateDate,validateRoom,validateCardDate and validateCard
now on submit of form I want to execute all of them.OR I want to execute 2nd if 1st is true such for all. I have implement some advise like:
return fun1() && fun2() && fun3(),
return fun1(); fun2(),
and made wrapper function too.. but could not get success.
UPDATE:MY CODE IS:
is their any mistake in code? every attempt has been failed so far.
function validateDate() {
var x = document.forms["form"]["checkin"].value;
var y = document.forms["form"]["checkout"].value;
if (x == y) {
alert("checkout date should be different from checkin");
return false;
}else if(x > y){
alert("checkout date should be greater");
return false;
}else{return true;}
}
function validateRoom() {
var a = document.forms["form"]["singleroom"].value;
var b = document.forms["form"]["doubleroom"].value;
var c = document.forms["form"]["tripleroom"].value;
if (a == 0 && b==0 && c==0) {
alert("Please select atleast one field");
return false;
}else{return true;}
}
function validateCardDate() {
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
var today = new Date();
if(year < today.getFullYear()){
alert("Card is expired");
return false;
}else if(year == today.getFullYear()){
if(month <= today.getMonth())
alert("Card is expired");
return false;
} else {return true;}
}
function validateCard() {
var cardType = document.forms["card"]["cardType"].value;
var cardNumber = document.forms["card"]["cardNumber"].value;
if(cardType == "visa"){
var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid Visa credit card number!");
return false;
}
}else if(cardType == "americanexpress"){
var cardno = /^(?:3[47][0-9]{13})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid Amercican Express credit card number!");
return false;
}
}else if(cardType == "mastercard"){
var cardno = /^(?:5[1-5][0-9]{14})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid mastercard credit card number!");
return false;
}
}
else if(cardType == "jcb"){
var cardno = /^(?:(?:2131|1800|35\d{3})\d{11})$/;
if(cardNumber.match(cardno))
{
return true;
}
else
{
alert("Not a valid JCB credit card number!");
return false;
}
}
}
Simply do:
function main(){
//functions to exexute.
}
Then do:
onsubmit="main()"
If you want to execute the second if the first is true then
The first function must return true
if(main()){if(//otherfunction){}}
Try this:
if (func1()){
if(func2()){
if(func3()){
return func4()
}else{
return false;
}
}else{
return false
}
}else{
return false
}
Every functions func1...func4 should be return a false or true value.
Create a new function which has all those four functions inside it
Example:
function ParentFunction() {
validateDate()
validateRoom()
validateCardDate()
validateCard()
}
An onSubmit call the ParentFunction(). This way you can even use arguments and decision controls to run those functions in any sequence you like.
UPDATE
Try this:
var validateDate = function () {
// Statements
return true // if conditions are what you want
}
var validateRoom = function () {
// Statements
return true // if conditions are what you want
}
var validateCardDate = function () {
// Statements
return true // if conditions are what you want
}
var validateCard = function () {
// Statements
return true // if conditions are what you want
}
function ParentFunction() {
if (validateDate() == true) {
if (validateRoom() == true) {
if (validateCardDate() == true) {
if (validateCard() == true) {
return true
}
}
}
}
return false
}
Hope it helps!

JavaScript. Please advise on better code reuse and/or structure

As the title suggests, A better coding structure or implementation for my JavaScript below. This checks a ID element values from a form before submitting to a database.
I'm interested to know if I could have reduced the code size/could have implemented reuse of code which will give me some tips for the future!
Thanks.
function validateRunnerID()
{
var runnerID = document.getElementById('RunnerID').value;
if (isNaN(runnerID) || runnerID < 1 || runnerID > 9999)
{
return "RunnerID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateEventID()
{
var eventID = document.getElementById('EventID').value;
if (isNaN(eventID) || eventID < 1 || eventID > 9999)
{
return "EventID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateDate()
{
var checkDate= /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/;
var date= document.getElementById('Date');
var tof= date.value.match(checkDate);
return tof? "" : "Date: Enter a Valid Date with parameters: YYYY-MM-DD \n\n";
}
function validateFinishTime()
{
var finishTime = document.getElementById("FinishTime").value;
if (finishTime.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/))
{
return ""
}else{
return "Finish Time: Enter a valid Time with parameters: HH:MM:SS \n\n";
}
}
//
//
function validatePosition()
{
var position = document.getElementById('Position').value;
if (position.length == 0)
{
document.getElementById('Position').value = -1;
return "";
}else{
return "";
}
}
function validateCategoryID()
{
var categoryID = document.getElementById('CategoryID').value;
if (categoryID.length == 0)
{
document.getElementById('CategoryID').value = -1;
return "";
}else{
return "";
}
}
function validateAgeGrade()
{
var ageGrade = document.getElementById('AgeGrade').value;
if (ageGrade.length == 0)
{
document.getElementById('AgeGrade').value = -1;
return "";
}else{
return "";
}
}
function validatePB()
{
var pBest = document.getElementById('PB').value;
if (pBest.length == 0)
{
document.getElementById('PB').value = 0;
return "";
}else{
return "";
}
}
//
//
function validateForm()
{
var result = validateRunnerID() + validateEventID() + validateDate() + validateFinishTime() + validatePosition() + validateCategoryID() + validateAgeGrade() + validatePB();
if ( result == "" )
{
alert("Data Accepted and Submitted \n\n");
return true;
}else{
alert("Please Fix Errors Listed: \n\n" + result);
return false;
}
}
One thing you can do is to accept an elementId as input to your validation functions. This allows to reuse the same logic for different fields.
For example:
function validate4DigitInt(elementId)
{
var value = document.getElementById(elementId).value;
if (isNaN(value) || value < 1 || value > 9999)
{
return elementId + ": Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
Now you can validate both RunnerId and EventId using the same function:
var result="";
result+=validate4DigitInt("RunnerId");
result+=validate4DigitInt("EventId");

Javascript redirect URL

Below is a bit of script I'm using in related to a form for a site. I'm trying to get it to redirect to a specific page if the first two functions aren't valid.
What's happening is that the redirect is happening even if the functions are valid
I'm sure I'm missing something really simple here...
Any help appreciated!
(function(){
var f1 = fieldname2,
valid_pickup_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if( AND(f1,f2))
{
if( valid_pickup_postcode(f1) && valid_dropoff_postcode(f2))
{
return 'Please select the vehicle you require for your delivery';
}
else
{
return window.location.href = "http://www.bing.com";
}
}
else
{
return '';
}
})()
(function() {
var f1 = fieldname2,
valid_pickup_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if (AND(f1, f2)) {
if (valid_pickup_postcode(f1) && valid_dropoff_postcode(f2)) {
return 'Please select the vehicle you require for your delivery';
} else {
// return window.location.href = "http://www.bing.com";
window.location.replace("http://www.bing.com");
}
} else {
return '';
}
})()
window.location.replace("http://www.bing.com"); should do the trick
Update: I have made small changes to make your code work. For something that's as straightforward as validating pickup and dropoff postal codes, the JS isn't (or shouldn't be) very complicated :) Here's a simpler version that will work
function myValidator(f1, f2) {
// Validate pickup postal code
function pickup_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
// Validate dropoff postal code
function dropoff_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
if (pickup_postcode(f1) === true && dropoff_postcode(f2) === true) { // If both pickup and dropoff postal codes are ok return a message prompting vehicle selection
return 'Please select the vehicle you require for your delivery';
} else { // Invalid pickup or dropoff postal code
// Redirect to website because either pickup or dropoff postal code is invalid
window.location.replace("https://www.bing.com");
}
}
myValidator("X909EF", "X909EE"); // Call it this way

multiple validation error for a textbox using jquery

I want to print specific emty error message as well as number error message for the age field while during the button click. for my code only the last error message is diplaying.
This is for Validation Purpose.
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnSubmit.ClientID %>").click(function () {
var error = 0;
var name = $('#<%=txtName.ClientID%>').val();
if ($.trim(name) == '') {
$('#name_error_msg').text('Name cannot be Empty');
$('#name_error_msg').parent().show();
error = 1;
} else
$('#name_error_msg').text('');
var country = $('#<%=ddlCountry.ClientID%>').val();
if (country == 0) {
$('#country_error_msg').text('Please select the Country');
$('#country_error_msg').parent().show();
error = 1;
}
else
$('#country_error_msg').text('');
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!filter.test(emailReg)) {
$('#email_error_msg').text('Invalid email format');
$('#email_error_msg').parent().show();
error = 1;
}
else {
$('#email_error_msg').text('');
}
var email = $('#<%=txtEmail.ClientID%>').val();
if ($.trim(email) == '') {
$('#email_error_msg').text('Email cannot be Empty');
$('#email_error_msg').parent().show();
error = 1;
} else {
$('#email_error_msg').text('');
}
if (!($('#<%=ChkAgree.ClientID%>').is(':checked'))) {
error = 1;
$('#check_error_msg').html("Please Tick the Agree to Terms of Use.");
$('#check_error_msg').parent().show();
}
else
$('#check_error_msg').html(" ");
if (error) {
return false;
} else {
return true;
}
});
});
</script>
All you need to do is, replace:
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
with:
var filter = /^[0-9-+]+$/;
var age = $('#<%=txtAge.ClientID%>').val();
if ( $.trim(age) == '' || !filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
} else {
$('#age_error_msg').text('');
}
You could create a temp variable to add up each error.
var age_errors = [];
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
age_errors.push('Age is empty');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
age_errors.push('Invalid Age number');
$('#age_error_msg').parent().show();
error = 1;
}
// set the error: empty string or a comma-separated list.
$('#age_error_msg').text(age_errors.join(', '));

Form validation not checking against expression

Here is my code, i cant figure out where its broken. It operates as if it never checks the variables for the correct regex that is written. Any help figuring out where im going wrong would be greatly appreciated.
<script>
function allNumbers( field, msg ) {
var numberexp = /^[0-9]+$/;
if ( field.value.match( numberexp ) ) {
return true;
} else {
alert( msg );
field.focus();
return false;
}
}
function allLetters( field, msg ) {
var letexp = /^[a-zA-Z]+$/;
if ( field.value.match( letexp ) ) {
return true;
} else {
alert( Msg );
field.focus();
return false;
}
}
function notEmpty( field, msg ) {
if ( field.value.length == 0 ) {
alert( msg );
field.focus();
return false;
}
return true;
}
function validateForm() {
var a = document.getElementById('firstname');
var b = document.forms["contactrecord"]["lastname"].value;
var c = document.forms["contactrecord"]["phone"].value;
var d = document.forms["contactrecord"]["address"].value;
var e = document.forms["contactrecord"]["city"].value;
var f = document.forms["contactrecord"]["state"].value;
var g = document.forms["contactrecord"]["zip"].value;
if ( allLetters( a, "Incorrect First Name" ) ) {
if ( allLetters( b, "Incorrect Last Name" ) ) {
if ( allNumbers( c, "Incorrect Phone Number" ) ) {
if ( notEmpty( d, "Incorrect address" ) ) {
if ( allLetters( e, "Incorrect City Name" ) ) {
if ( allNumbers( g, "Incorrect Zip Code") ) {
return true;
}
}
}
}
}
}
return false;
}
</script>
This isn't how I would do it, but it's your code. You were passing the value of each form control whereas the functions are expecting a reference to a form control.
Note that the function now expects a reference to the form, so you can do something like:
<form onsubmit="validateForm(this);" ...>
function allNumbers(field, msg) {
// If has a non-number character, return false
if (/\D/.test(field.value)) {
field.focus();
return false;
}
return true;
}
// If value has a non-word character, return false
function allLetters(field, msg) {
if (/\W/.test(field.value)) {
field.focus();
return false;
}
return true;
}
// If value has no characters, return false
function notEmpty(field, msg) {
if (field.value.length == 0){
alert(msg);
field.focus();
return false;
}
return true;
}
function validateForm(form) {
var a = document.getElementById('firstname');
var b = form.lastname;
var c = form.phone;
var d = form.address;
var e = form.city;
var f = form.state;
var g = form.zip;
if (allLetters(a, "Incorrect First Name") &&
allLetters(b, "Incorrect Last Name") &&
allNumbers(c, "Incorrect Phone Number") &&
notEmpty(d, "Incorrect address") &&
allLetters(e, "Incorrect City Name") &&
allNumbers(g, "Incorrect Zip Code")
) {
return true;
}
return false;
}
My guess is you're missing name attributes in your inputs. Put them in there.

Categories