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/
Related
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>
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!.
I have the following form, my question is implementing a fadding JQuery Alert message without using the normal js alertBox
the Html Form
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName: <input type="text" name="username" placeholder="Username">
password: <input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
javaScript code
<script>
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
if (y == null || y == "") {
alert("Password must be filled out");
return false;
}
}
</script>
You can simply add a div and display your error message within that div and use fadeIn and fadeOut to animate the same.
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
if (y == null || y == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
To be more optimized
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
showAlert("Name must be filled out");
return false;
}
if (y == null || y == "") {
showAlert("Password must be filled out");
return false;
}
}
function showAlert(message) {
$(".alert").find('.message').text(message);
$(".alert").fadeIn("slow", function() {
setTimeout(function() {
$(".alert").fadeOut("slow");
}, 4000);
});
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
Why not make your own?
A simple fadeIn() and fadeOut() can create a really cool "alert-box" and is super easy to use :)
Login Page:-
First You have to Create Your Login Code & at Last use header() with URL get Variable.
<?php
header('Location:view.php?status=login');
?>
Dashboard Page:-
<?php
if(isset($_GET['status']) == 'login'){
echo '<div class="alert alert-success">
Login Successfully !!!
</div>';
}
?>
jQuery Part:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" rel="stylesheet">
$('document').ready(function(){
$(".alert").fadeIn(1000).fadeOut(5000);
});
</script>
My HTML:
<html>
<head>
<title>Js</title>
<link href="js1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="box">
<form action="action.php">
<label>Enter Name
<input id="Username" type="text" name="Enter Username" />
</label>
<div id="feedback"></div>
<label id="pass">Password
<input id="pass" type="password" name="Enter Passkey" />
</label>
<input type="submit" value="sign up" />
</form>
</div>
<script src="js1.js"></script>
</body>
</html>
My JavaScript:
function checkUsername() { // Declare function
var elMsg = document.getElementById('feedback'); // Get feedback element
if (this.value.length < 5) { // If username too short
elMsg.textContent = 'Username must be 5 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear message
}
}
var elUsername = document.getElementById('Username'); // Get-name input
elUsername.onBlur = checkUsername; // loses focus call checkuserName()
My CSS:
body{
background-color:black;
}
#box{
background-color:silver;
height:600px;
width:600px;
margin-left:300px;
}
p{
color:white;
font-size:18;
}
form{
padding:20px;
width:96px;
}
input[type="text"] , input[type="password"]
{
background-color:#999;
border:2px solid white;
}
input[type="text"]:focus , input[type="password"]:focus
{
background-color:#fff
}
What the program is supposed to do :
Once the user is done entering the UserName, the function must check if it has atleast 5 characters else display a msg in place of "feedback"?
What am I missing?
You have a typo in this line
var elUsername = document.getElementById('username')
The id of the input is uppercase Username
try:
var elUsername = document.getElementById('Username')
And another more important typo onBlur event in elUsername.onBlur = checkUsername should be onblur all lowercase.
Here is a working Example
I have searched and applied almost every code I could get but nothing seems to work.
I am trying to implement validation and I just wanted that as soon as I press Enter on the Password field, it will access the submit button ALONG WITH the function being called..
Here is my entire (FAIRLY LONG :D ) code
<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script>
function reset()
{
document.forms['testform'].reset();
document.getElementById("x1").focus();
}
function passfocus()
{
document.getElementById("x2").focus();
}
function passreset()
{
document.getElementById("x2").value="";
document.getElementById("x2").focus();
}
function Result()
{
var user=document.getElementById("x1").value;
var pass1=document.getElementById("x2").value;
passw=+pass1;
var at=user.indexOf("#");
var dot=user.lastIndexOf(".");
var sub=user.substring(user.length, dot+1);
for(i=0;i<sub.length;i++)
{
var d=sub.charAt(i);
if(d==='0' || d===',' || d==='?' ||d===';' || d===':' || d==='+' || d==='=' || d==='-' || d==='1' ||d==='2' || d==='!' ||d==='#' ||d==='#' ||d==='$' ||d==='%' ||d==='^' ||d==='&' ||d==='*'|| d==='(' || d===')'|| d==='3' ||d==='4' ||d==='5' ||d==='6' ||d==='7' ||d==='8' ||d==='9')
var d1=0;
else
var d1=1;
}
var count=0;
for(j=0;j<user.length;j++)
{
var d2=user.charAt(j);
if(d2=='#')
count=count+1;
}
var flag=0;
for(k=0; k<(user.length-1); k++)
{
if(user.charAt(k)==='.' && user.charAt(k+1)==='.')
flag=1;
}
if(!user)
{
alert("Field is mandatory");
}
else if(d1===0)
{
alert("E-mail not valid");
reset();
}
else if(count===2)
{
alert("E-mail not valid");
reset();
}
else if(at<1 || dot<at+2 || dot+2>=user.length)
{
alert("E-mail not valid");
reset();
}
else if (flag===1)
{
alert("E-mail not valid");
reset();
}
else
{
if(passw===0)
{
alert("Please enter password");
passfocus();
}
else if(pass1.length<8)
{
alert("Password must be greater than 8 characters");
passreset();
}
else
{
alert("you have successfully submitted the form");
reset();
}
}
}
</script>
</head>
<style>
p.serif{font-family:"Times New Roman",Times,serif;}
.sansserif{font-family:Arial,Helvetica,sans-serif;}
.td1{text-align:middle;}
table,td,th
{
border:1px solid red;
}
table
{
width:100%;
}
th
{
height:50px;
}
td
{
padding:15px;
}
</style>
<body style="background-color:AntiqueWhite;">
<h2 align="middle" style="background-color:White;"><font color="MediumVioletRed">Student Login</font></h2>
<p align="middle" class="sansserif" style="background-color:yellow;"><b><i><font color="Maroon">Enter Student Credentials below to login</font></i></b></p>
<table border="1" >
<th>CREDENTIALS</th>
<tr>
<td class="sansserif">
<form name="testform" align="middle"
<div style="color:#006400" class="myCustomDiv">
E- mail ID: <input type="text" name="usern" id="x1">
<br>
Password: <input type="password" name="pass" id="x2" >
<br>
<button type="button" onclick="Result()" align="middle" id="x3">Login</button>
</div>
</form>
</td>
</tr>
</table>
</body>
</html>
Just for detailing, I didn't shorten it. It is very basic I know, I'd be really thankful if anyone could help.
You have terrible errors in your html. There is a <style> element between the </head> and the <body>. Things like that are a no-no!
And the definition for the form is not complete: you are missing the > on the start tag, as well as the action attribute. The latter is mandatory and is the cause for the inability to submit.
Other than that, you have other errors, like in the javascript.
What does, for instance, passw=+pass1 mean?
But all those are secondary to the problems with the form start tag. Repair those first, then you can test properly, because submit will work.