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
Related
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!
I have made 2 variables named username and password and I want to test if they are both true but the prompt does not seem to pop up. I do not understand, I also am pretty new to code and really want to learn how to do this
var 1 = false;
var 2 - false;
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
1 = true;
} else {
1 = false;
}
if (password == "Wout2003!") {
2 = true;
} else {
2 = false;
}
};
if (1 = false && 2 = false) {
alert("Wrong Password and Username!");
login();
}
There is so much wrong with your code, this should work though.
What you got wrong is:
You cannot set variables using the - operator
You cannot compare in an if-statement using single =
You cannot name variables with numbers.
var unc = false; // username correct
var pwc = false; // password correct
while (!login());
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
unc = true;
} else {
unc = false;
}
if (password == "Wout2003!") {
pwc = true;
} else {
pwc = false;
}
if (unc && pwc){
return true;
} else {
return false;
}
};
var 1 = false;
means that a variable called 1 will get the value of false. But this is syntactically incorrect. It is invalid to name your variables with integer names. You are also confused about the meaning of =, which is the assignment operator. Let's see a simplified solution:
var uCorrect = false;
var pCorrect = false;
function login() {
uCorrect = (prompt("Username") == "wouterXD");
pCorrect = (prompt("Password") == "Wout2003");
if ((!uCorrect) && (!pCorrect)) {
alert("Wrong Password and Username!");
}
return uCorrect && pCorrect;
}
while (!login());
Or an extremely simplified solution, if you do not need to store these data:
function login() {
return (prompt("Username") == "wouterXD") && prompt("Password") == "Wout2003";
}
while (!login());
So many things are wrong with this code...
First of all, never name your variables as integers... so rename them to something more... suitable.
Secondly, your var 2 is wrong. You've got a subtraction sign not an equals.
Least but not last, your logical operator is also wrong.
Single equals sign is assigning values, in your if statement you should check if they are the same, so a double sign is needed like so
if(firstVariable == false && secondVariable == false){
}
You won't achieve the functionality you want anyway after correcting those mistakes. The last operator (the one I posted above) is outside the function body, i.e. it won't execute when the function is ran.
var firstVariable = false;
var secondVariable = false;
function login() {
var username = prompt("Username");
var password = prompt("Password");
if (username == "wouterXD") {
firstVariable = true;
} else {
firstVariable = false;
}
if (password == "Wout2003!") {
secondVariable = true;
} else {
secondVariable = false;
}
if (firstVariable = false && secondVariable = false) {
alert("Wrong Password and Username!");
login();
}
};
Can someone please tell me how to add my below JavaScript (function validateEmail() to the JavaScript I already created (function validateForm()? I need to combine the 2 into one. What I did was create a JavaScript to create error messages, then my new one creates an error message if the Email field was typed incorrectly. The longer JavaScript is what needs the shorter one. Do I just add an else if, if than? I am new to JavaScript. Thank you for those that help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
NEW JAVASCRIPT
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}
Your final function should look like below:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
ret &= validateEmail();
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}
EDIT
If you can not (or dont want to) change validateForm function to include call to validateEmail then you can specify both functions in the form onsubmit
onsubmit="return validateForm() && validateEmail()"
Your form validation script simply needs to call your additional function as an additional test.
Try adding this to the end of your main function:
if(!validateEmail()) {
// error code
ret=false;
}
else {
// ok
}
return ret;
$("#pincode").blur(function () {
var pincode = $("#pincode").val().trim();
var pattern = /^[0-9]{6}$/;
if (pincode != "" && !IsPatternFormate(pincode, pattern)) {
$("#pincode").addClass('invalidValidation');
document.getElementById('pincode')
.setCustomValidity('please enter data in proper formate');
}
});
var IsPatternFormate = function (value, pattern) {
var match = pattern.test($(value));
console.log(match);
}
i don't know why, match always return me false value.
var IsPatternFormate = function (value, pattern) {
if(pattern.test(value)){
return true;
}else{
false;
}
}
Change your IsPatternFormate function
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;
}