onclick validation not stopping POST to MVC controller - javascript

I am trying to integrate a realex payment API and have used the example found on https://developer.realexpayments.com/#!/integration-api/3d-secure/java/html_js#3dsecurity-accordion and as part of this I have set up the following page:
<!DOCTYPE html>
<html>
<head>
<title>Basic Validation Example</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/rxp-js.js"></script> <!-- Available at https://github.com/realexpayments -->
<!-- Basic form styling given as an example -->
<style type="text/css">
label {
display: block;
font-size: 12px;
font-family: arial;
}
input {
width: 200px;
}
input.small {
width: 50px;
}
.twoColumn {
float: left;
margin: 0 30px 20px 0;
}
.clearAll {
clear: both;
}
</style>
</head>
<body>
<!-- Basic HTML form given as an example -->
<form name="myForm" method="POST" autocomplete="off" action="securepayment">
<p>
<label for="cardNumber">Card Number</label>
<input type="text" id="cardNumber" name="card-number" />
</p>
<p>
<label for="cardholderName">Cardholder Name</label>
<input type="text" id="cardholderName" name="cardholder-name" />
</p>
<p class="twoColumn">
<label>Expiry Date</label>
<input type="text" id="expiryDateMM" name="expiry-date-mm" aria-label="expiry date month" placeholder="MM" class="small" />
<input type="text" id="expiryDateYY" name="expiry-date-yy" aria-label="expiry date year" placeholder="YY" class="small" />
</p>
<p class="twoColumn">
<label for="cvn">Security Code</label>
<input type="text" id="cvn" name="cvn" class="small" />
</p>
<p class="clearAll">
<input value="Pay Now" type="submit" name="submit" onclick="validate();" />
</p>
</form>
<script>
// Basic form validation using the Realex Payments JS SDK given as an example
function validate() {
alert("VALIDATE HIT !!!!")
var cardNumberCheck = RealexRemote.validateCardNumber(document.getElementById('cardNumber').value);
var cardHolderNameCheck = RealexRemote.validateCardHolderName(document.getElementById('cardholderName').value);
var expiryDate = document.getElementById('expiryDateMM').value.concat(document.getElementById('expiryDateYY').value) ;
var expiryDateFormatCheck = RealexRemote.validateExpiryDateFormat(expiryDate);
var expiryDatePastCheck = RealexRemote.validateExpiryDateNotInPast(expiryDate);
if ( document.getElementById('cardNumber').value.charAt(0) == "3" ) { cvnCheck = RealexRemote.validateAmexCvn(document.getElementById('cvn').value);}
else { cvnCheck = RealexRemote.validateCvn(document.getElementById('cvn').value); }
if (cardNumberCheck == false || cardHolderNameCheck == false || expiryDateFormatCheck == false || expiryDatePastCheck == false || cvnCheck == false)
{
// code here to inform the cardholder of an input error and prevent the form submitting
if (cardNumberCheck == false) { alert("CARD IS FALSE") }
if (cardHolderNameCheck == false) { alert("CARD HOLDER NAME IS FALSE") }
if (expiryDateFormatCheck == false) { alert("EXPIRY DATE FORMAT IS FALSE") }
if (expiryDatePastCheck == false) { alert("EXPIRY DATE IS IN THE PAST") }
if (cvnCheck == false) { alert("CVN IS FALSE") }
return false;
}
else
return true;
}
</script>
</body>
</html>
Despite ensuring that the javascript is working as expected I have checked to see that the appropriate validation messages are being displayed in alerts which they are however the post to the controller is never cancelled despite the onclick() event resulting in a return false
Can anyone see why this is happening or am I doing something wrong?

Try changing your onclick event handler from onclick="validate();" to onclick="return validate();" that will fix this issue.
Hope this helps!.

Related

Inline error message still displayed after the user adds text to input fields

When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});

How do I prevent form fields from clearing out?

I have a form in an HTML page with a script that checks the fields in the form, the problem is that whenever I write something "wrong" in the field and the script gives an alert(), all the fields of the form clear out.
Here's the code:
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
<link rel="icon" href="loginIcon.png">
<script src="script.js"></script>
</head>
<body>
<form id="form" method="POST">
<div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
<div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
<div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
<div class="center"><button onclick="check()">LOGIN</button></div>
Don't have an account yet? Sign Up
</form>
</body>
</html>
And the script:
function check() {
var em = document.getElementById("email").value.trim()
var ps = document.getElementById("pass").value.trim()
var ch = document.getElementById("check")
if (ch.checked) {
if (em == "" || em == undefined) {
alert("Email missing")
return false
} else if (ps == "" || ps == undefined) {
alert("Password missing")
return false
} else {
if (!em.includes("#")) {
alert("Missing '#'")
return false
} else if (ps.length > 16) {
alert("Password must be 16 characters or less")
return false
} else {
document.getElementById("form").action = "check.php"
}
}
} else {
alert("You're a Robot!")
return false
}
}
Change your form to this
<form id="form" action="check.php" method="POST" onsubmit="return check()">
<div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
<div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
<div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
<div class="center"><button type="submit">LOGIN</button></div>
Don't have an account yet? Sign Up
</form>
Right now, the form is submitted after the alert, you need to have this event on form submission so that in case of false, form submission is halted.
onsubmit receives a boolean (true by default) so if you return false from the function, the submission will be halted (as done here).

PHP Form Validation with Javascript doesnt stop on return false

I have been trying to make a simple HTML form validation via Javascript
I have been struggling with this for a while now over a few examples, And no matter what I follow, My index page keeps loading after the button click on the form, I believe that I have put return false in the correct locations to break the rest of code execution, Any ideas why this is so? "My" code is below
Note: I have tried the novalidate attribute with the form, this deactivates the browser's validation but still sends me through to my index page, The ideal functionality should not load the index page and stay on the register page with warnings below the correct input fields
index.php
<?php
if (isset($_POST["register"]))
{
$user = $_POST["username"];
echo "Welcome ".$user;
}
?>
register.php
<!DOCTYPE html>
<html>
<head>
<title>Form validation with javascript</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<form novalidate method="POST" action="index.php" onsubmit="return Validate()" name="vform">
<div>
<input type="text" name="username" class="textInput" placeholder="Username">
<div id="name_error" class="val_error"></div>
</div>
<div>
<input type="email" name="email" class="textInput" placeholder="Email">
<div id="email_error" class="val_error"></div>
</div>
<div>
<input type="password" name="password" class="textInput" placeholder="Password">
</div>
<div>
<input type="password" name="password_confirmation" class="textInput" placeholder="Password confirmation">
<div id="password_error" class="val_error"></div>
</div>
<div>
<input type="submit" value="Register" class="btn" name="register">
</div>
</form>
</div>
</body>
</html>
<!-- Adding javascript -->
<script type="text/javascript">
// GETTING ALL INPUT TEXT OBJECTS
var username = document.forms["vform"]["username"];
var email = document.forms["vform"]["email"];
var password = document.forms["vform"]["password"];
var password_confirmation = document.forms["vform"]["password_confirmation"];
// GETTING ALL ERROR DISPLAY OBJECTS
var name_error = document.getElementId("name_error");
var email_error = document.getElementId("email_error");
var password_error = document.getElementId("password_error");
// SETTING ALL EVENT LISTENERS
username.addEventListener("blur", nameVerify, true);
email.addEventListener("blur", emailVerify, true);
password.addEventListener("blur", passwordVerify, true);
// Validation Function
function Validate(){
// Username Validation
if (username.value == ""){
username.style.border = "1px solid red";
name_error.textContent = "Username is required";
username.focus();
return false;
}
// Email Validation
if (email.value == ""){
email.style.border = "1px solid red";
email_error.textContent = "email is required";
email.focus();
return false;
}
// Password Validation
if (password.value == ""){
password.style.border = "1px solid red";
password_error.textContent = "password is required";
password.focus();
return false;
}
// check if the two passwords match
if (password.value != password_confirmation.value)
{
pasword.style.border = "1px solid red";
pasword_confirmation.style.border = "1px solid red";
password_error.innerHTML = "The two passwords dont match";
return false;
}
}
// event handler functions
function nameVerify(){
if (username.value != "")
{
username.style.border = "1px solid #5E6E66";
name_error.innerHTML = "";
return true;
}
}
function emailVerify(){
if (email.value != "")
{
email.style.border = "1px solid #5E6E66";
email_error.innerHTML = "";
return true;
}
}
function passwordVerify(){
if (passwprd.value != "")
{
passwprd.style.border = "1px solid #5E6E66";
passwprd_error.innerHTML = "";
return true;
}
}
</script>
style.css
#wrapper{
width: 35%;
margin: 50px auto;
padding: 20px;
background: #EFFFE0;
}
form{
width: 50%;
margin: 100px auto;
}
form div{
margin: 3px auto;
}
.textInput{
margin-top: 2px;
height: 28px;
border: 1px solid #5E6E66;
font-size: 16px;
padding: 1px;
width: 100%;
}
.btn{
padding: 7px;
width: 100%;
}
.val_error{
color: #FF1F1F;
}
Thanks a bunch for any help you can provide!
Assign an id to your form, attach form submit event to it and if validations get fails then you can use event.preventDefault(); to stop the submission of form.
Try the code below.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="your_file_name.php" method="post" id="myForm">
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname" >
<br><br>
<input type="submit" value="Submit">
</form>
$( "#myForm" ).submit(function(event) {
if($("#firstname").val()== "" || $("#lastname").val()== "") //Your validation conditions.
{
alert("Kindly fill all fields.");
event.preventDefault();
}
//submit the form.
});
</script>
</html>

Add CSS when there's an error

I have a simple login page that I'm having some trouble with. When you type in incorrect info it just runs an alert, but I want it to add some CSS to the backgrounds of the fields that makes them red. How would I go about editing the following code to do this?
Here's the fiddle.
Thanks.
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<title>Jeremy Blazé</title>
</head>
<body>
<div id="box">
<img src="logo.png" />
<form name="login">
<input type="text" name="userid" placeholder="Username" />
<input type="password" name="pswrd" placeholder="Password" />
<input type="submit" class="button" onclick="check(this.form)" placeholder="Password" value="Sign in" />
</form>
</div>
<script language="javascript">
function check(form) {
if(form.userid.value == "username" && form.pswrd.value == "password") {
window.open('dashboard/index.html')
}
else {
alert("Error Password or Username")
}
}
</script>
</body>
</html>
// js
else {
alert("Error Password or Username");
document.login.class = "error";
}
// css
form.error input[type="text"], form.error input[type="text"] {
background-color: red;
}
On error, you can do this:
form.userid.className = "invalid";
CSS
.invalid
{
border-style:solid;
border-width:2px;
border-color:red;
}
I would change your function slightly and run it on form onsubmit:
function check(form) {
var valid = true;
if (form.userid.value !== 'username') {
form.userid.className = 'error';
valid = false;
}
else {
form.userid.className = '';
}
if (form.pswrd.value !== 'password') {
form.pswrd.className = 'error';
valid = false;
}
else {
form.pswrd.className = '';
}
if (valid) {
window.open('dashboard/index.html');
}
return false; // return valid; if you want to submit the form once it's valid
}
HTML:
<form name="login" onsubmit="return check(this)">
CSS:
#box input.error {
border: 1px darksalmon solid;
background: #f0dddd;
}
Demo: http://jsfiddle.net/JLrQB/1/

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources