Here I use HTML and javascript please go through it don't want to change my whole code but just take a look.
there is an HTML file and a javascript file.
both are linked.
in a form, I am taking user name and password and checking or validating them if they are right I will let the user go to the next page or stop it there.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<style type="text/css">
#error{
color:red;
font-style: italic;
}
#success{
color:green;
font-style:italic;
}
</style>
</head>
<body>
<form method="post" onsubmit = "return(validateForm());">
Enter username : <input id='username' type='text' required>
Enter password : <input id='password' type='password' required>
<p id="error"></p>
<p id="sucess"></p>
<input type = "submit" value = "Login" />
</form>
</body>
<script type='text/javascript' src="functions.js"></script>
</html>
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
function validateForm(){
if (username == 'username' && password == 'password'){
document.getElementById('sucess').innerHTML = 'sucessful login';
return true;
}
else{
document.getElementById('error').innerHTML = 'invalid credentials';
return false;
}
}
function welcomeuser(){
document.getElementById('welcomemsg').innerHTML('Welcome ' +username);
}
Please try below solution
functions.js code as below
function validateForm(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == 'username' && password == 'password'){
document.getElementById('sucess').innerHTML = 'sucessful login';
// redirect code in page
// window.location.href = 'thankyou.html'
return false;
} else {
document.getElementById('error').innerHTML = 'invalid credentials';
return false;
}
}
Your HTML code as below
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<style type="text/css">
#error{
color:red;
font-style: italic;
}
#success{
color:green;
font-style:italic;
}
</style>
<script type='text/javascript' src="functions.js"></script>
</head>
<body>
<form method="post" onsubmit="return validateForm();">
Enter username : <input id='username' type='text'>
Enter password : <input id='password' type='password'>
<p id="error"></p>
<p id="sucess"></p>
<input type = "submit" value = "Login" />
</form>
</body>
</html>
Since you are submitting the form (using type=submit) your form skips the javascript validation. A quick fix is to change:
<input type = "submit" value = "Login" />
To:
<input type = "button" value = "Login" />
And you don't need this: onsubmit = "return(validateForm());" just call the function onclick or with event listener
Of course you need to get the values from the function in order to check it,
And then after checking if inputs are correct here:
if (username == 'username' && password == 'password'){
To do whatever you want (either redirect the user of actually submitting the form using submit() method).
I modify your code little and this should work:
document.querySelector('#submit').addEventListener('click', validateForm);
function validateForm(){
var username = document.querySelector('#username').value;
var password = document.querySelector('#password').value;
if (username === 'username' && password === 'password') {
document.querySelector('#sucess').textContent = 'sucessful login';
// redirect or submit
}
else {
document.querySelector('#error').textContent = 'invalid credentials';
}
}
#error{color:red; font-style: italic; }
#success{ color:green; font-style:italic; }
<form method="post">
Enter username : <input id='username' type='text' required>
Enter password : <input id='password' type='password' required>
<p id="error"></p>
<p id="sucess"></p>
<button id="submit" type="button">Login</button>
</form>
Related
I created a part of the simple website with a register page I created a validation (.js) for both and wanted to validate the input on the form so after i completed the validation criteria and fill all the input it supposed to link or open the next page (it's login page if you are in the register.html). The problem is if i don't include href to link it, it won't open the next page but the validation was successful but if i include href the validation was skipped and it instantly opens the next page which is login.html after i click on the Register button. How to put validation on the Register button so it validates the input and open the next page at the same time? (A message for a successful registration after that is also better). Here is the code for register and the register validation.
This is called registersraboet.html for the Register page.
<!DOCTYPE html>
<html>
<head>
<title>Register Sraboet</title>
<link rel="stylesheet" type="text/css"
href="css/register.css">
<script type="text/javascript" src="js/jquery-
latest.min.js"></script>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<div class="headerregister">
<img src="assets/logo.png">
</div>
<div class="containerregister">
<form action="" id="rgs_form">
<div id="err_msg"></div>
<label><b>Email</b></label><br>
<input type="email" placeholder="masukkan email
anda" id="emailrgs"><br>
<label><b>Username</b></label><br>
<input type="text" placeholder="masukkan nama
anda" id="usernamergs"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="masukkan
password anda" id="passwordrgs"><br>
<label><b>ID Number</b></label><br>
<input type="text" placeholder="masukkan nomor
KTP anda" id="KTPrgs"><br>
<label><b>Phone Number</b></label><br>
<input type="text" placeholder="masukkan nomor
telepon anda" id="phonergs"><br>
<div class="termsnprivacy">
<p>By creating an account you agree to
our Terms & Privacy</p>
</div>
<div class="registerbtn">
<button type="button"
onclick="validatergs()">Register</button><br>
</div>
<div class="alreadyakun">
<br><p>Sudah Punya Akun? Silahkan Login</p>
</div>
</form>
</div>
<div class="footerregister">
<div class="copyrightfooter">
<label for="Copyright">Copyright ©
Sraboet 2020</label>
</div>
</div>
<script type="text/javascript"
src="js/validationregister.js"></script>
</body>
</html>
This is called validationregister.js for the validation in register.
var err = document.getElementById('err_msg');
function validatergs(){
var email = document.getElementById('emailrgs').value;
var username =
document.getElementById('usernamergs').value;
var password =
document.getElementById('passwordrgs').value;
var ktp = document.getElementById('KTPrgs').value;
var phones = document.getElementById('phonergs').value;
if(email == ""){
err.innerHTML = "Email harus diisi!"
}
else if(username == ""){
err.innerHTML = "Nama harus diisi!"
}
else if(password == ""){
err.innerHTML = "Password harus diisi!"
}
else if(ktp == ""){
err.innerHTML = "Nomor ktp harus diisi!"
}
else if(!+(ktp)){
err.innerHTML = "nomor ktp harus angka!";
}
else if(phones == ""){
err.innerHTML = "Nomor telepon harus diisi!"
}
else if(!+(phones)){
err.innerHTML = "Nomor telepon harus angka!";
}
else {
a.href = "loginsraboet.html";
}
}
This is not the right way to write it. First you get the a node, use getelementByclass or some other method to trigger the node click() method such as let a= document.getelementbyid (#a);next a.click ()
I got this code made but i can't get it to validate the required fields with alert boxes for missing fields or submit to a pop up window like i'm trying to do. The code is supposed to validate certain fields that only show up when one of the radio buttons are clicked and a pop up window containing a url is supposed to show up after submission. Not working. Need help.
Code:
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
if(document.getElementById('businessCheck').checked) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var address=document.forms["myForm"]["address"];
var bname=document.forms["myForm"]["bname"];
var url=document.forms["myForm"]["url"];
var id=document.forms["myForm"]["tax"];
var rname=document.forms["myForm"]["rname"];
var email=documen.forms["myForm"]["email"];
if(address.value == "") {
alert("Please enter an address.");
address.focus;
return false;
}
if(bname.value == "") {
alert("Please enter a business name.");
bname.focus;
return false;
}
if(url.value == "") {
alert("Please enter a business URL.");
url.focus;
return false;
}
if(id.value == "") {
alert("Please enter a business tax ID.");
id.focus;
return false;
}
if(rname.value == "") {
alert("Please enter a residence name.");
rname.focus;
return false;
}
if(email.value == "") {
alert("Please enter an email address.");
email.focus;
return false;
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<center><h1>Fill the form below</h1>
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<center><p><b>Address: </b><input type="text" name="address"></p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business <input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence<br>
<div id="ifBusiness" style="display:none">
<b>Business Name: </b><input type="text" id="name" name="bname"><br>
<b>Business Website URL: </b><input type="text" id="url" name="url"><br>
<b>Business Tax ID: </b><input type="text" id="tax" name="tax"><br>
<input type="submit" value="Submit">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b><input type="text" id="name" name="rname"><br>
<b>Email: </b><input type="text" id="email" name="email"><br>
<input type="submit" value="Submit"></center>
</div>
</form>
<hr>
<hr>
</body>
</html>
The alert boxes are not popping up and I'm not sure how to fix it.
As per the comments, I have added the if-clause checking for business or not.
I also added the code to open the form submission into a new window.
Finally I cleaned up all the things you should not use anymore, like obsolete HTML tags like <b> and <center> and such, adding comments when appropriate.
<!DOCTYPE html>
<html>
<head>
<title>
<h1>Javascript Assignment</h1>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h2>Fill the form below</h2>
</title>
<!-- center tag is deprecated and should be replaced by CSS -->
<style>
head {
text-align: center;
}
.bold {
font-weight: bold;
}
</style>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<span class="bold">Address: </span>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<span class="bold">Name: </span>
<input type="text" id="name" name="rname">
<br>
<span class="bold">Email: </span>
<input type="text" id="email" name="email">
</div>
<!-- missed the closing </div> -->
</div>
</div>
<!-- Only one submit button per form -->
<input type="submit" value="Submit">
</form>
<hr>
<hr>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
<!-- both scripts can be in the same <script> tag -->
<script>
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if ( is_business ) {
document.getElementById('ifBusiness').style.display='block';
document.getElementById('ifResidence').style.display='none';
}
else {
document.getElementById('ifBusiness').style.display='none';
document.getElementById('ifResidence').style.display='block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if ( address.value == "" ) {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the banem, tax and url if a business is selected
if ( is_business ) {
if ( bname.value == "" ) {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
// It does not make sense to call the tax id "id", tax is a better name.
if ( tax.value == "" ) {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if ( url.value == "" ) {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if ( rname.value == "" ) {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if ( email.value == "" ) {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open( '', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234' );
// Set the form target to the name of the newly created popup.
var form = document.querySelector( 'form[name="myForm"]' );
form.setAttribute( 'target', 'SELU' );
// Continue as normal
return true;
}
</script>
</body>
</html>
this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!
Here is my js. I am trying to create an email form validation and it isn't working. Every time submit is clicked it automatically sends you to google(which is where it is supposed to send you if the input is valid) even if it just blank or incorrect.
var txtEmail = document.querySelector("email");
var txtFeedback = document.querySelector('#txtFeedback');
var errorDivs = document.getElementsByClassName("error");
formReference.addEventListener('submit', onFormSubmit);
function onFormSubmit(event) {
var isValid = true;
//clear out the feedback div
txtFeedback.innerHTML = "";
//clear out the error divs
for(var i = 0; i < errorDivs.length; i++) {
errorDivs[i].innerHTML = "";
}
if ( txtEmail.value == "" || !/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txtEmail.value)){
isValid = false;
txtFeedback.innerHTML += "<p>Please enter a valid email address.</p>";
txtEmail.nextElementSibling.innerHTML = "Please enter a valid email address."
} if(!isValid) {
event.preventDefault();
}
}
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#txtFeedback {
color: #FF0000;
}
.error {
display: inline;
color: #FF0000;
}
</style>
</head>
<body>
<div id="txtFeedback"></div>
<form action="http://www.google.com" id="myForm">
<div>
<label for="email">Email:</label>
<input id="email"/>
<div class="error"></div>
</div>
<div>
<input type="submit" value="submit" id="btnSubmit" />
</div>
</form>
<script src = "js/main.js"></script>
</body>
</html>
your first line selects email elements.
change it to select element with id of email:
var txtEmail = document.querySelector("#email");
and you didn't declared formReference in your code.
I declared it like this and it works just fine.
var formReference = document.getElementById('myForm');
I want to make a loginform using pure javascript (no libraries) and I have 2 problems!
SOLVED! by Grainier Perera
When username.value.length hits 4 characters usernameInfo.innerHTML changes back to "Please type ypur username" ! The problem is passwordInfo.innerHTML changes to "At least 6 characters" as soon as username.value.length hits 4 characters. So here is my first problem. I want passwordInfo.innerHTML to change only when I start typing in password field (onkeyup).
My second problem. When I submit the form with empty fields I want both usernameInfo.innerHTML and passwordInfo.innerHTML to change, not only usernameInfo.innerHTML.
To make it easier for u to understand the code I'll paste it all here so you can just copy it and try it yourself. Thank you!
<!DOCTYPE html>
<html>
<head>
<style>
form label {display:block; margin-top:5px;margin-left:3px;font:12px Arial;color:gray;}
form input {width:200px;padding:5px;display:inline-block; margin-top:5px;}
#submit {padding:7px;background-color:#f7af38; border:#f7af38;width:215px;display:inline-block;margin-top:15px;font:11px Tahoma;color:black;}
#usernameInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#passwordInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#finalInfo {font:italic 12px Arial; margin-left:5px;}
</style>
</head>
<body>
<form method="post" action="login.php" onsubmit="return validate();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validate();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validate();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
<script type="text/javascript">
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validate()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
}
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
}
}
</script>
</div>
</body>
</html>
Try This
HTML
<form method="post" action="login.php" onsubmit="return validateForm();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validateUserName();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validatePassWord();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
JavaScript
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validateUserName()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
return true;
}
}
function validatePassWord()
{
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
return true;
}
}
function validateForm()
{
var userValid = validateUserName();
var passValid = validatePassWord();
return userValid && passValid;
}
Working Sample : link