Form validation not checking against expression - javascript

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.

Related

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

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

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

Javascript: Problems with invoking functions within a function

I am trying to clean up this spaghettified code and I decided to separate the methods into separate functional objects and then call them within a single validate function. The code runs correctly on the first function and returns an alert box correctly. However, when I fix the first alert and resubmit the form the second function fires an alert at me to fix something, I click okay and immediately get an alert on the third function. Obviously I need to put in some code to stop the program from running after I click okay to the second functions alert so I can fix the issue, but how?
var checkboxes = document.getElementsByName('days');
var valid = false;
function textFieldValid(){
var textFieldsReq = document.getElementsByName('textFieldReq');
for( var i=0;i<9;i++ ){
if ( !textFieldsReq[i].value ){
alert ( 'You need to fill in the required* text field!' );
textFieldsReq[i].focus();
return false;
}
}
};
function checkboxesValid(){
for ( var i = 0;i<checkboxes.length;i++ ){
if ( checkboxes[i].checked ) {
valid = true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one day!' );
checkboxes[0].focus();
return false;
}
}
function lodgeValid(){
var lodging = document.getElementsByName('lodge');
for( var i=0; i<lodging.length; i++ ){
if( lodging[i].checked ){
valid=true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one option!' );
lodging[0].focus();
return false;
}
}
function validate(textFieldsReq){
textFieldValid();
checkboxesValid();
lodgeValid();
};
You need to return true/false from each of the tests and then
var checkboxes = document.getElementsByName('days');
function textFieldValid() {
var textFieldsReq = document.getElementsByName('textFieldReq');
for (var i = 0; i < 9; i++) {
if (!textFieldsReq[i].value) {
alert('You need to fill in the required* text field!');
textFieldsReq[i].focus();
return false;
}
}
//if valid return true
return true;
};
function checkboxesValid() {
//create local variables
var valid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one day!');
checkboxes[0].focus();
return false;
}
//if valid return true
return valid;
}
function lodgeValid() {
var lodging = document.getElementsByName('lodge'),
valid = false;
for (var i = 0; i < lodging.length; i++) {
if (lodging[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one option!');
lodging[0].focus();
return false;
}
//if valid return true
return valid;
}
function validate(textFieldsReq) {
//check whether all the tests are turnig true
return textFieldValid() && checkboxesValid() && lodgeValid();
};

Form doesn't return true and won't send to PHP

So the validation for the form works, but I cannot get it to send to the php file. I'm assuming it has something to do with the return false/true and the end.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '')
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
if (email == '')
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
if (msg == '')
{
$('.msgerror').html('What can we help you with?').fadeIn(1000);
}
return false;
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
I think your last section of code should read like this:
if($.trim($('.nameerror').text()) == '')
{
// You can do stuff here first if everything is good.
return true;
}
else
{
// Or you can do stuff here for a failed submission.
return false;
}
You are exiting the function before the last if statement is checked.
You must use this code:
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '') {
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
return false;
}
if (email == '') {
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
return false;
}
if (msg == '') {
$('.msgerror').html('What can we help you with?').fadeIn(1000);
return false;
}
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
Instead of checking to see if a particular element has html in it... why don't you just set a flag? This makes everything a bit more simplistic.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
var flag = true;
//do this for each of your if statements
if(there is an error case) {
//do whatever you want to the DOM
flag = false;
}
return flag;
}

Categories