2

I have a page that verifies credit card credentials. It's all well and good until I need to redirect the user to a another page.

function vNumarCard(numar)
{
    console.log(numar);
  var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
  if(!numar.match(/^(?:4[0-9]{12}(?:[0-9]{3})?)/))
        {
      return false;
        }
      else
        {
        
        return true;
        }
}

function vDataExp(data){
    console.log(data);
    if(!data.match(/(0[1-9]|1[0-2])[/][0-9]{2}/)){
        
        return false;
    }
    else{
        
        var d = new Date();
        var anCurent = d.getFullYear();
        var lunaCurenta = d.getMonth() + 1;
        var parti = data.split('/');
        var an = parseInt(parti[1], 10) + 2000;
        var luna = parseInt(parti[0], 10);
         if (an < anCurent || (an == anCurent && luna < lunaCurenta)) {
             alert("Card expirat!")
            return false;
         }
         
         return true;

}
}

function vCVC(cvc){
    console.log(cvc);
    if(!cvc.match(/[0-9][0-9][0-9]/)){
        
        return false;
    }
    else{
        return true;
    }
}

function verCard(numar,data,cvc){
    if(vNumarCard(numar)==true&&vDataExp(data)==true&&vCVC(cvc)==true){
        alert('inside if');
        location.href = '/success.html';
    }
    else if(vNumarCard(numar)==false) alert("Numarul cardului este invalid!");
        else if(vDataExp(data)==false) alert("Data expirarii este invalida");
            else alert("CVC incorect!");
}

function verDate(){
    var numar = document.getElementsByName("numarCard")[0].value;
    var data = document.getElementsByName("dataExp")[0].value;
    var cvc = document.getElementsByName("codCVC")[0].value;

    verCard(numar,data,cvc);
}
<!DOCTYPE html>
<html lang="ro">
<head>
	<title>Cumpara</title>
<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="node_modules/bootstrap/scss/bootstrap.css">
	
</head>
<body>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark justify-content-center">
				<ul class="navbar-nav">
					<li class="nav-item">
						<a class="nav-link" href="index.html">Acasă</a>
					</li>
					<li class="nav-item">
						<a class="nav-link" href="modele.html">Modele</a>
					</li>
					
					<li class="nav-item">
						<a class="nav-link" href="galerie.html">Galerie</a>
					</li>
					<li class = "nav-item">
						<a href="cos.html" class = "nav-link">
          					<span class="glyphicon">&#128722;</span>
       					 </a>
					</li>
				</ul>
				
	</nav>

<div class="container">
	<div class="row">
		<div class="col-sm-4">
		</div>
		<div class="col-sm-4">
			<h2 style="text-align: center;">Cumpara produsele selectate</h2>
			<form method="POST">
				
				<div class="form-group">
					<label for="email">
						Email:
					</label>
					<input type="email" name="email" class="form-control" placeholder="Email">
					
				</div>
				<div class="form-group">
					<label for="numeCumparator">
						Nume:
					</label>
					<input type="text" name="numeCumparator" class="form-control" placeholder="Nume">
					
				</div>
				<div class="form-group">
					<label for="numarCard">
						Numar Card:
					</label>
					<input type="text" name="numarCard" class="form-control" placeholder="1234 1234 1234 1234">
					
				</div>
				<div class="form-group">
					<label for="dataExp">
						Data de expirare:
					</label>
					<input type="text" name="dataExp" class="form-control" placeholder="ll/aa">
					
				</div>
				<div class="form-group">
					<label for="codCVC">
						CVC:
					</label>
					<input type="text" name="codCVC" class="form-control" placeholder="CVC">
					
				</div>
				<button name="cumpara" type="submit" class="btn btn-success btn-lg btn-block" onclick="verDate();">Cumpara</button>
			</form>
		</div>
		<div class="col-sm-4"></div>
	</div>
</div>

<script src="node_modules/jquery/dist/jquery.min.js"></script>
	<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
	<script src="scripturi/cumpara.js"></script>
</body>
</html>

Every function works corectly, I checked each of them and I used the alert to see if the if works and it does. I used the same method on other pages and it works well but location.href doesn't work. I have also tried with document.location.href and window.location but I get the same result. What actually happens is that the same page gets reloaded instead of getting redirected.

9
  • 1
    just a hint, not answering the question. There's no need to type vNumarCard(numar) == true, you can just write fun1() && fun2() && fun3() Commented May 23, 2020 at 12:09
  • where is success.html in project ? try "/success.html" Commented May 23, 2020 at 12:10
  • Thanks for the hint! success.html is at the same location. Commented May 23, 2020 at 12:12
  • "doesn't work" isn't a helpful description (if it worked you wouldn't ask). Have you checked your browser developer tools? Commented May 23, 2020 at 12:21
  • I have checked and I have no errors or warnings. And I don't know how to explain the problem better than I already did. Commented May 23, 2020 at 12:31

3 Answers 3

1

What happens is that your form gets submitted when clicking the submit button. Since your form doesn't have an action attribute, the form gets submitted to the current URL which is why the same page reloads. Event handlers are executed before the default action (the form submission) so even though you try to redirect in your event handler, this gets overridden by the form submission which is why the redirect gets cancelled.

The solution is to prevent the form submission. First of all, you should use the onSubmit listener on the form instead of the onClick listener on the button. You don't have to do it like that but it's considered good practice and it helps with accessibility.
You need to pass in the event argument to your function, like this:

<form onSubmit="verDate(event);">

In your verDate() function, you now use that event object to prevent the form submission, like this:

function verDate(event){
    event.preventDefault();
    var numar = document.getElementsByName("numarCard")[0].value;
    var data = document.getElementsByName("dataExp")[0].value;
    var cvc = document.getElementsByName("codCVC")[0].value;

    verCard(numar,data,cvc);
}

That should solve your issue, but I would also like to suggest that a much cleaner way of doing this is to instead of explicitly redirecting, you set the success page as the action attribute of the form (i.e. <form action="/success.html">) and rather than redirecting when the form is valid, you run event.preventDefault() only when the form is invalid. That's the proper way of working with forms, utilizing the default behavior as much as possible.

Also, pro-tip: if you want to get a higher grade on your JS assignment, use addEventListener() to add your event listeners instead of adding them as inline attributes in the HTML.

Sign up to request clarification or add additional context in comments.

Comments

0

You should be using return true for your function

function vNumarCard(numar) {
 //validation code
 return true;
 }

function vDataExp(data) {
 //validation code
 return true;
 }

function vCVC(cvc) {
 //validation code
 return true;
 }

And then you can use this:

if ( vNumarCard(numar) && vDataExp(data) && vCVC(cvc) ) {
  location.href = 'success.html';
}

Comments

0
<button name="cumpara" type="submit" onclick="verDate();">Cumpara</button>

You have a button with two jobs:

  • Run your code (validation + redirect)
  • Submit the form

So I guess the browser is doing both things. Since both actions involve loading a (different) page, only the last one that manages to complete "wins".

If you don't really plan to submit form data to server you should change the type="submit" attribute to type="button".

In any case, it's unclear why you have a form in the first place since you seem to discard its values altogether. I presume you have some additional process you haven't shared (such as an AJAX call).

2 Comments

Thanks for the answer but it doesn't seem to solve the issue. The story behind the form is that for the project I had to make, I needed to get, and check, data from the user. At first I used php, but later I found out that the php part wasn't going to be graded, so I had to make everything again using javascript.
Getting rid of the type attribute won't help because buttons within a form are of type submit by default. He needs to explicitly set type="button" for it to work. Btw, using a form when you have form elements is always a benefit since it helps with accessibility and such meta things, so it's better to "decorate" the form to behave the way you want and potentially degrade gracefully than to not work within the context of a form at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.