JavaScript form validation without alert - javascript

HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<div class="page-header">
<h1 align="center" class="header">ONLINE ADMISSION FORM </h1>
</div>
<form role="form" method="post" name="sign_up_form" onSubmit=" return validateForm()">
<div class="container">
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter User Name">
</div>
<span id="usernameError"></span>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<span id="emailError"></span>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<span id="passwordError"></span>
<div class="form-group">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="conf_password" name="conf_password" placeholder="Confirm Password">
</div>
<span id="confError"></span>
<input id="button" type="submit" name="signup" value="Sign-Up" >
</div>
</form>
</body>
</html>
JavaScript
<script type="text/javascript">
function validateForm()
{
var username = checkUsername();
var email = checkEmail();
var password = checkPassword();
var conf = checkConf();
}
// Validate the fill in of First Name
function checkUsername(){
var userName=document.forms["sign_up_form"]["username"].value;
if (userName==null || userName=="")
{
document.getElementById("usernameError").innerHTML = "Not a valid e-mail address";
return false;
}
else{
return true;
}
function checkEmail()
{
// code for email validation starts here
var Email=document.forms["sign_up_form"]["email"].value;
var atpos=Email.indexOf("#");
var dotpos=Email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=Email.length)
{
var error=document.forms["sign_up_form"]["emailError"].innerHtml="Not a valid e-mail address";
return false;
}
else {
return true;
}
}
//code for email validation ends here
function checkPassword()
{
var Password=document.forms["sign_up_form"]["password"].value;
if (Password==null || Password=="")
{
var error=document.forms["sign_up_form"]["passwordError"].innerHtml="Choose Password";
}
return false;
else {
return true;
}
}
function checkConf()
{
var confirm_password=document.forms["sign_up_form"]["conf_password"].value;
if(confirm_password==null || confirm_password=="")
{
var error=document.forms["sign_up_form"]["confError"].innerHtml="Confirm Password";
return false;
}
else {
return true;
}
}
</script>
What's wrong this JavaScript? Why doesn't it display an error message?

you are missing one closing brace...
function checkUsername(){
var userName=document.forms["sign_up_form"]["username"].value;
if (userName==null || userName==""){
document.getElementById("usernameError").innerHTML = "Not a valid e-mail address";
return false;
}
else{
return true;
} // missing this
}

onSubmit=" return validateForm()"
should not be capitalized for S
onsubmit=" return validateForm()"

Related

POST method does not pass the value password from the input field

Here form is submitted via POST method but password given in the input field of type=password not assigning to 'upassword' given in the userregister function.When I print the 'upassword' it gives an output "None".Also it gives an error like this when I give JAVASCRIPT validation.
Internal Server Error: /Salon/Registration/
Traceback (most recent call last):
File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Project\salon\user\views.py", line 53, in salonregister
epassword = sha256(spassword.encode()).hexdigest()
AttributeError: 'NoneType' object has no attribute 'encode'
HTML file:
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<title>Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="{% static 'styles/style.css' %}" rel="stylesheet"/>
<script src="jquery-3.5.1.min.js"></script>
</head>
<body>
<section class="sreg" id="sreg">
<div class="container-fluid">
<div class="htop">
<h4>Register Form</h4>
</div>
<div class="row">
<div class="col-12">
<form method="POST" name="contact" action="{%url 'salonregister' %}">
{%csrf_token%}
<div class="form-row">
<div class="form-group col-md-6">
<label for="fname">First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="First Name">
<span id="lfname"></span>
</div>
<div class="form-group col-md-6">
<label for="lname">Last Name</label>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name">
<span id="llname"></span>
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
<span id="lemail"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="pass" placeholder="Password">
<span id="lpass"></span>
</div>
<div class="form-group">
<label for="cpassword">Confirm Password</label>
<input type="password" class="form-control" id="cpassword" name="cpass" placeholder="Confirm Password">
<span id="lcpass"></span>
</div>
<div class="form-group">
<label for="mobile">Mobile</label>
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile">
<span id="lmob"></span>
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" id="address" name="address" rows="3" placeholder="Address"></textarea>
<span id="laddress"></span>
</div>
<center>
<button type="submit" class="btn btn-success" onsubmit="return register()">Submit</button>
</center>
</form>
{% for msg in messages %}
<center>
<h4 style="color:red;">{{msg}}</h4>
</center>
{% endfor %}
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="{% static 'js/scriptfunction.js' %}"></script>
</body>
</html>
Javascript:
function register()
{
if(document.contact.fname.value=="")
{
document.getElementById("lfname").innerHTML="Enter Your First Name";
return false;
}
else
{
var regName = /^[a-zA-Z]+$/;
if(document.contact.fname.value.match(regName))
document.getElementById("lfname").innerHTML="";
else
{
document.getElementById("lfname").innerHTML="Inavalid Name";
return false;
}
}
if(document.contact.lname.value=="")
{
document.getElementById("llname").innerHTML="Enter Your Last Name";
return false;
}
else
{
var regName = /^[a-zA-Z]+$/;
if(document.contact.lname.value.match(regName))
document.getElementById("llname").innerHTML="";
else
{
document.getElementById("llname").innerHTML="Inavalid Name";
return false;
}
}
if(document.contact.email.value=="")
{
document.getElementById("lemail").innerHTML="Enter Email ID";
return false;
}
else
{
document.getElementById("lemail").innerHTML="";
var mailformat = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(document.contact.email.value.match(mailformat))
document.getElementById("lemail").innerHTML="";
else
{
document.getElementById("lemail").innerHTML="Invalid Email";
return false;
}
}
if(document.contact.pass.value=="")
{
document.getElementById("lpass").innerHTML="Enter Password";
return false;
}
else
{
var pregexp=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
if(document.contact.pass.value.match(pregexp))
document.getElementById("lpass").innerHTML="";
else
{
document.getElementById("lpass").innerHTML="Contains eight characters,upper&lowercase letter,digit&special characters";
return false;
}
}
if(document.contact.cpass.value=="")
{
document.getElementById("lcpass").innerHTML="Enter Password";
return false;
}
else
{
document.getElementById("lcpass").innerHTML="";
if(document.contact.pass.value!=document.reg.cpass.value)
{
document.getElementById("lcpass").innerHTML="Password Mismatch";
return false;
}
else
document.getElementById("lcpass").innerHTML="";
}
if(document.contact.mobile.value=="")
{
document.getElementById("lmob").innerHTML="Enter Your Mobile Number";
return false;
}
else
{
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(document.contact.mobile.value.match(phoneno))
document.getElementById("lmob").innerHTML="";
else
{
document.getElementById("lmob").innerHTML="Invalid Mobile Number";
return false;
}
}
if(document.contact.address.value=="")
{
document.getElementById("laddress").innerHTML="Enter Your Address";
return false;
}
else
document.getElementById("laddress").innerHTML="";
}
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth import login,logout
from hashlib import sha256
from user.models import salonlogin,clientlogin,salonreg,clientreg, salondetails,bookingdetails,reviews,contact
from django.contrib import messages
def salonregister(request):
if request.method == 'POST':
sfname = request.POST.get('fname')
slname = request.POST.get('lname')
semail = request.POST.get('email')
spassword = request.POST.get('password')
scpassword = request.POST.get('cpassword')
epassword = sha256(spassword.encode()).hexdigest()
smobile = request.POST.get('mobile')
saddress = request.POST.get('address')
if (salonreg.objects.filter(Email=semail).exists()):
messages.info(request, "Email ID Already Taken")
return redirect('salonregister')
elif (spassword != scpassword):
messages.info(request, "Password Doesn't Match")
return redirect('salonregister')
elif (salonreg.objects.filter(Mobile=smobile).exists()):
messages.info(request, "Mobile Number Already Taken")
return redirect('salonregister')
else:
sloginobj = salonlogin()
sloginobj.Username = semail
sloginobj.Password = epassword
sloginobj.save()
ssalondetails = salondetails()
ssalondetails.Login_id = sloginobj
ssalondetails.save()
ssalonreg = salonreg()
ssalonreg.Login_id = sloginobj
ssalonreg.First_name = sfname
ssalonreg.Last_name = slname
ssalonreg.Email = semail
ssalonreg.Password = epassword
ssalonreg.Mobile = smobile
ssalonreg.Address = saddress
ssalonreg.save()
ssalondetail = salonreg.objects.get(Email=semail)
slid = ssalondetail.id
fsname = ssalondetail.First_name
lsname = ssalondetail.Last_name
request.session["sid"] = slid
return render(request, "owner.html", {'fsname': fsname , 'lsname': lsname})
else:
return render(request, "register.html")
urls.py
from django.urls import path,re_path
from . import views
urlpatterns=[
path('Salon/Registration/', views.salonregister, name="salonregister"),
]
You access password and cpassword while the name you set for these fields is actually pass and cpass:
<input type="password" class="form-control" id="password" name="pass" placeholder="Password">
<input type="password" class="form-control" id="cpassword" name="cpass" placeholder="Confirm Password"> ​
It will work if you change your code to use the correct field names:
​spassword = request.POST.get('pass')
​scpassword = request.POST.get('cpass')
You could have spotted that by looking at the actual data that is getting sent in the POST request, so my suggestion for the future is to always first inspect your request in the browser's devtools.
You are submitting pass and cpass, not password and cpassword, so change it to:
spassword = request.POST.get('pass')
scpassword = request.POST.get('cpass')

validate popup, then open another popup

I am using bootstrap to create a popup signup form. Once the user clicks submit and it has been validated I want to close that popup and open another saying thank you. I have tried using .modal('show') in popupvalidation.js but that did not seem to work. All it did was open both at the same time.
Here is the code:
index.php
<form name="popup" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return popupValidation();" method="post">
<div class="row">
<input name="firstName" type="text" class="form-control" id="inputFirstName" placeholder="First Name">
<input name="lastName" type="text" class="form-control" id="inputLastName" placeholder="Last Name">
</div>
<div class="row">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="youremail#email.com">
</div>
<div class="row">
<input name="password" type="password" class="form-control" id="inputPassword" placeholder="password">
</div>
<div class="row">
<input name="repeatPass" type="password" class="form-control" id="retypePassword" placeholder="Retype password">
</div>
<div class="row">
<input name="trainer" type="checkbox"/> Sign up as trainer
</div>
<div class="modal-footer popup-footer">
<p id="error">Please make sure all fields are filled out</p>
<input type="submit" class="btn btn-default submit" value="Register">
</div>
</form>
popupvalidation.js
function popupValidation() {
var fname = document.forms["popup"]["firstName"].value;
var lname = document.forms["popup"]["lastName"].value;
var pass = document.forms["popup"]["password"].value;
var repass = document.forms["popup"]["repeatPass"].value;
var email = document.forms["popup"]["email"].value;
if (fname==null || fname=="") {
document.getElementById("inputFirstName").focus();
document.getElementById("error").innerHTML= 'Please enter your First Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (lname==null || lname=="") {
document.getElementById("inputLastName").focus();
document.getElementById("error").innerHTML= 'Please enter your Last Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (email==null || email=="") {
document.getElementById("inputEmail").focus();
document.getElementById("error").innerHTML= 'Please enter a valid email';
document.getElementById("error").style.display = 'block';
return false;
}
if (pass==null || pass=="") {
document.getElementById("inputPassword").focus();
document.getElementById("error").innerHTML= 'Please enter a password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass==null || repass=="") {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Please retype password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass!=pass) {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Passwords do not match';
document.getElementById("error").style.display = 'block';
return false;
}
}

onSubmit redirect to website depenfing on value

Hi I'm trying to create a simple login form with 2 or 3 users where depending on who is logging in the redirect should be to different urls.
My code so far:
HTML
<h1 class="title">Logga in</h1>
<div class="grid__container">
<form name="login" onSubmit="return validateForm();" action="some website url" method="post" class="form form--login">
<div class="form__field">
<label class="fontawesome-user" for="login__username"><span class="hidden">Username</span></label>
<input name="usernameInput" id="login__username" type="text" class="form__input" placeholder="Username" required>
</div>
<div class="form__field">
<label class="fontawesome-lock" for="login__password"><span class="hidden">Password</span></label>
<input name="passwordInput" id="login__password" type="password" class="form__input" placeholder="Password" required>
</div>
<div class="form__field">
<input type="submit" value="Sign In">
</div>
</form>
</div>
JavaScript
function validateForm() {
var username = document.login.usernameInput.value;
var password = document.login.passwordInput.value;
var username1 = "user 1";
var password1 = "1234";
var username2 = "user 2";
var password2 = "4321";
if ((username == username1) && (password == password1)){
return "www.google.se";
}else if (username == username2) && (password == password2) {
return "www.facebook.se";
}else{
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}

Validating login form using javascript

I'm relatively new to HTML and JS and I've been trying to create a simple login page that on entering valid credentials redirects to index.html page. But no matter what I enter it always redirects to the index.html page. Here's the HTML code for the login page
<form role="form" action="index.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<div class="form-group">
<label class="sr-only" for="form-username">Username</label>
<input type="text" name="form-username" placeholder="Username..." class="form-username form-control" id="form-username">
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Password</label>
<input type="password" name="form-password" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<button type="submit" class="btn" value="submit">Sign in!</button>
</form>
Here's the javascript
<script type="text/javascript">
function check_info()
{
var myform = document.formlogin;
if(myform.form-username.value == "test")
{
if(myform.form-password.value == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
P.S: I'm using a bootstrap login template.
Html:
onsubmit="return check_info()"
Javascript:
function check_info()
{
var user = document.getElementById("form-username").value;
var pass = document.getElementById("form-password").value;
if(user == "test")
{
if(pass == "123")
{
return true;
}
}
return false;
}
You can use required parameter like this:
<input type="text" name="form-username" placeholder="Username..." class="form-username form-control" id="form-username" required>

Execute PHP Submit button Only if Javascript is true

I am trying to execute the mysql query using PHP form. Below is the form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="signup.css" type="text/css">
<script type="text/javascript" src="form_val.js"></script>
<title>Untitled Document</title>
</head>
<body bgcolor="#0ca3d2">
<div align="right">
<h2>Go back</h2>
</div>
<div class="form-style-10">
<h1>Sign Up Now!<span>Sign up and tell us what you think of the site!</span></h1>
<form action="#" method="post" name="myForm" onSubmit="CheckTerms()">
<div class="section"><span>1</span>First Name & Address</div>
<div class="inner-wrap">
<input type="text" name="First_Name" placeholder="Enter First Name" id="fname">
<label id="error" style="color:red"></label>
<input type="text" name="Last_Name" placeholder="Enter last Name"/>
<label id="error_l" style="color:red"></label>
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="section"><span>2</span>Email </div>
<div class="inner-wrap">
<input type="text" name="Email_i" placeholder="enter email here" id="e_mail" />
<label id="error_e" style="color:red"></label>
<button type="button" name="validate" onclick="loadDoc(this.value)">Validate</button>
<div id="check"></div></div>
<div class="section"><span>3</span>Passwords</div>
<div class="inner-wrap">
<input type="password" name="pass" placeholder="Must be 6 to 15 characters" id="Pass" onBlur="PassCheck()" />
<label id="error_p" style="color:red"></label>
<input type="password" name="repass" placeholder="Retype Password" id="RePass"/>
<label id="error_rp" style="color:red"></label>
<span class="privacy-policy">
<input type="checkbox" name="terms" value="value1" id="check_box">Agree to Terms and Conditions
</span>
<input type="submit" name="signup" value="Register" id="sub_button">
<label id="error_lable" style="color:red"></label>
</div>
</form>
</div>
</body>
I have the below form validation in Javascript,
function CheckTerms(){
var letter = /^[a-zA-Z ]*$/;
if(document.myForm.First_Name.value.match(letter) && document.myForm.First_Name.value =="")
{
document.getElementById("error").innerHTML = "* Please Provide First Name";
document.myForm.First_Name.focus();
return false;
}
if(document.myForm.Last_Name.value.match(letter) && document.myForm.Last_Name.value =="" )
{
document.getElementById("error_l").innerHTML = "* Please provide your Last name!";
document.myForm.Last_Name.focus() ;
return false;
}
var email =/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if(document.myForm.Email_i.value.match(email) && document.myForm.Email_i.value=="")
{
document.getElementById("error_e").innerHTML = "* Please provide your EMAIL!";
document.myForm.Email_i.focus() ;
return false;
}
var min = 6;
var max = 15;
if(document.myForm.pass.value.length < min || document.myForm.pass.value.length > max)
{
document.getElementById("error_p").innerHTML = "Password Should be betweeen 6 to 15 characters";
document.myForm.pass.focus() ;
return false;
}
var pass = document.getElementById("Pass").value;
var re = document.getElementById("RePass").value;
if(pass != re)
{
document.getElementById("error_rp").innerHTML = "Password do not match";
return false;
}
if(document.getElementById("check_box").checked == false)
{
document.getElementById("error_lable").innerHTML = "Please Check";
return false;
}}
<?php
session_start();
include "config.php";
if(isset($_POST['signup']))
{
// my logic here
}
?>
but the problem is, even the javascript returns the error, clicking the submit button , executes PHP script resulting the data entry into database. I want to stop form submission if any of the javascript error exists.
You are not returning the boolean in the event even though you are doing it in the function. onSubmit receives true by default and submits it.
Change
onsubmit="CheckTerms()"
to
onsubmit="return CheckTerms()"

Categories

Resources