javascript validate allows submit even if there an error - javascript

I have HTML form with javascript validation but whenever i submit the form error message appear even if the form fields are correct(not empty or null)
I want the error message to appear only when form fields are empty or null when i submit the form
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<link type="text/css" href="/css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Javascript Form Validation</title>
<style>
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="card">
<div class="card-body">
<form method="post" name="myForm" id="myForm">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control" name="name" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter name">
</div>
<button type="submit" name="login" class="btn btn-primary">Submit</button>
</form>
<script>
class User
{
constructor(userName,submitButton)
{
this.userName = document.myForm.name.value;
this.submitButton = document.getElementById("myForm");
}
submitForm()
{
this.submitButton.onsubmit = function()
{
if(this.userName == "" || this.userName == null)
{
document.write("Name Required");
return false;
}
}
}
}
let user = new User();
user.submitForm();
</script>

Prefer to code this way:
<form method="post" id="my-form">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control"
name="userName"
aria-describedby="nameHelp"
placeholder="Enter name" >
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
const myForm = document.getElementById("my-form")
myForm.onsubmit=event=>
{
if(myForm.userName.value.trim()==='')
{
event.preventDefault()
alert("Name Required")
}
}
or, with a JS class (in HTML / JS everything is allready OBJECT, even a form)
class User {
constructor(formID,uName) {
this.myForm = document.getElementById(formID)
this.u_Name = this.myForm[uName]
// this.myForm.onsubmit = e => this.doSubmit(e)
this.myForm.addEventListener('submit', this.doSubmit.bind(this))
}
doSubmit(e) {
if(this.u_Name.value.trim()==='') {
e.preventDefault()
alert("Name Required")
}
}
};
let user = new User('my-form','userName');
class User {
constructor(formID,uName) {
this.myForm = document.getElementById(formID)
this.u_Name = this.myForm[uName]
// this.myForm.onsubmit = e => this.doSubmit(e)
this.myForm.addEventListener('submit', this.doSubmit.bind(this))
}
doSubmit(e) {
if(this.u_Name.value.trim()==='') {
e.preventDefault()
alert("Name Required")
}
}
};
let f_User = new User('my-form','userName')
<form method="post" id="my-form">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control"
name="userName"
aria-describedby="nameHelp"
placeholder="Enter name" >
</div>
<button type="submit" name="login" class="btn btn-primary">Submit</button>
</form>

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')

Bootstrap 4 manually invalidate input field natively

I want to make use of Bootstrap 4's form validation. From what I read you can invalidate a field by adding class 'is-invalid' - this works, but when I want to check the form validity using method checkValidity() it still says the form is VALID which is not what I expected. I was hoping of making use of the native bootstrap 4 functionality and not use plugins such as jquery validator etc.
$('#submit_button').on('click', function(e){
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if (form.checkValidity() === false) {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form is-invalid" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 1:
Using JQUERY you can use the .val() function
To get the value of the input field with id "taskname_in" use this code
$('#taskname_in').val()
Option 1 snippet:
$('#submit_button').on('click', function(e) {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if ($('#taskname_in').val() == '') {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 2:
Using form validator to check all input-fields at once.
Option 2 snippet:
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>
'is-invalid' does not make that particular field an invalid. it just applies CSS to look as it's invalid.
Result of HTMLElement.checkValidity() depends on its Constraint.
Suppose, you add field with 'required' constrain and you run checkValidity() on the form or field while it's empty, you will receive response as false, which means that a form or field is not valid.
In your case, just add required in your input field and you will receive response as invalid if you submit form while field is empty.
If you have the default Bootstrap validation code for the required fields:
$(".needs-validation").submit(function() {
var form = $(this);
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
});
You would just need to add another validation for example on input and use the setCustomValidity. For example if you want to check for equal values on password and confirm password:
if ($('form input[name="confirm_password"').length > 0) {
$('input[name="confirm_password"').on('change paste keyup', function() {
var password = $(this).closest('form').find('input[name="password"').val();
if($(this).val() !== password){
this.setCustomValidity('Passwords must match');
} else {
this.setCustomValidity('');
}
});
};
If you have an invalid-feedback message next to the input element it will show that message instead of the one you set here.

Onsubmit in form does not called

I have next form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function submit(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
<form role="form" method="post" onsubmit="return submit($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></input>
</form>
This script checks whether passwords are the same.
But using firefox debugger i can't find that it goes into this method.
Is this problem with script? Or Is ths problem about declaring onsubmit handler?
There was many problems:
change value to val
use another name for submit function, it's kinda reserved
use this instead of $('#PasswordChange form')
use var first_pass = $('.first_try'); instead of find
you forgot to write else
and you need use event.preventDefault(); to stop refreshing page or submiting page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function save(form) {
var first_pass = form.querySelector('.first_try');
var second_pass = form.querySelector('.second_try');
if (first_pass.value == second_pass.value) {
alert('its ok');
return true;
} else {
first_pass.value = '';
second_pass.value = '';
first_pass.placeholder = 'Пароли не совпадают';
first_pass.style.borderColor='red';
second_pass.style.borderColor='red';
return false
}
}
</script>
<form role="form" method="post" onsubmit="event.preventDefault(); return save(this)">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password"
placeholder="Новый пароль"
required>
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password"
placeholder="Повтор пароля"
required>
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"/>
</form>
Use this code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitData(form) {
var first_pass = form.find('.first_try');
var second_pass = form.find('.second_try');
if (first_pass.value == second_pass.value) {
return true
}
first_pass.value = '';
second_pass.value = '';
first_pass.attr('placeholder', 'Пароли не совпадают');
first_pass.css('border-color', 'red');
second_pass.css('border-color', 'red');
return false
}
</script>
</head>
<body>
<form role="form" method="post" onsubmit="return submitData($('#PasswordChange form'))">
<h3>Редактирование пользователя</h3>
<div class="form-group"> <input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required></div>
<div class="form-group"> <input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required></div><input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить"></form>
</body>
</html>
Please change submit function name because it is keyword so it is not use it. Also remove </input> next to submit button
Use this :
onsubmit="return submit(this)"
You should not return anything if you don't need to cancel the submit action. Also you could use submit form event handler with jQuery .submit() method instead of hanler definition in onsubmit attribute.
$("form").submit(function(e) {
var passwords = $('[name=password]');
if (passwords.eq(0).val() !== passwords.eq(1).val()) {
alert("Пароли не совпадают!");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" method="post" action="/">
<h3>Редактирование пользователя</h3>
<div class="form-group">
<input type="password" class="form-control first_try" name="password" placeholder="Новый пароль" required >
</div>
<div class="form-group">
<input type="password" class="form-control second_try" name="password" placeholder="Повтор пароля" required />
</div>
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Отправить" />
</form>
Also I recommend you to use Bootstrap validation states instead of input's border style setting.

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()"

Bad url after a sign up HTML, Javascript

I have a problem. I implemented a signup and a login page. I have the correct url (localhost:3000/login and localhost:3000/signup). But I have a problem. I enter in the signup and I insert the data of the user then if you press the button you are redirecting to localhost:3000/login but I have this error:
Cannot GET /login?firstname=a&lastname=a&username=a&email=a%40e.i&password=a&repeatPassword=a
In practice, when I press the button, all the data that the user has inserted are also added to the url. How is it possible? Can you help me please? Here is my code:
SIGNUP.DUST
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Signup</title>
<link rel="stylesheet" href="css/standardize.css">
<link rel="stylesheet" href="css/base.css">
<script src="js/app.js"></script>
<script src="js/ajax.js"></script>
<script src="js/library.js"></script>
<script src="js/model.js"></script>
<script src="js/utils.js"></script>
</head>
<body class="body signup">
<div class="vertical-align-wrapper">
<div class="vertical-align-box">
<h1 class="slogan">Now listen.</h1>
<div class="form-signup-wrapper">
<form action="/login" method="GET" class="form-signup">
<input class="form-control form-stacked" name="firstname" placeholder="Firstname" type="text" required="true" id="Firstname">
<input class="form-control form-stacked" name="lastname" placeholder="Lastname" type="text" required="true">
<input class="form-control form-stacked" name="username" placeholder="Username" type="text" required="true" id="username">
<input class="form-control form-stacked" name="email" placeholder="email" type="email" required="true">
<input class="form-control form-stacked" name="password" id="password" placeholder="Password" type="password" required="true" >
<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password" onkeyup="enable()" required="true">
<input class="btn btn-beats btn-block btn-stacked" value="Sign up" id = "btnPlaceOrder" type="submit" onclick="setuplogin()">
</form>
<p>Already have an account? <strong>login</strong> now!</p>
</div>
</div>
</div>
<h1 class="fat blue-glow bottom-right">Atelier<span class="pulse" style="display:inline-block;">Beats.</span></h1>
LOGIN.DUST
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="css/standardize.css">
<link rel="stylesheet" href="css/base.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="js/dust-core.min.js"></script>
<script src="/views/views.js"></script>
<script src="js/app.js"></script>
</head>
<body class="body login">
<div class="vertical-align-wrapper">
<div class="vertical-align-box">
<h1 class="slogan">Gotta <i class="fa fa-heart beats pulse" style="color:#B13A3D;"></i> that sound.</h1>
<div class="form-login-wrapper">
<form action="library.html" class="form-login">
<input class="form-control form-stacked" name="username" placeholder="Username" type="text" required="true" id="username">
<input class="form-control form-stacked last" name="password" placeholder="Password" type="password" required="true" id="password" onkeyup="validation()">
<input class="btn btn-beats btn-block btn-stacked" value="Tune in" type="submit" id="submit">
</form>
<p>Don't have an account? <strong>sign up</strong> now! </p>
</div>
</div>
</div>
<h1 class="fat blue-glow bottom-right">Atelier<span class="pulse" style="display:inline-block;">Beats.</span></h1>
</body>
</html>
APP.JS (where are all my function that I'm using)
function setuplogin(){
var userName = document.getElementById("username").value;
var password = document.getElementById("password").value;
var data = {
userName : userName,
password : password
};
console.log(data);
doJSONRequest("POST", "/users/", null, data, function(){
document.location = location.location;
});
}
function validation(){
var userName_login = document.getElementById("username").value;
var password_login = document.getElementById("password").value;
var data = {
userName : userName_login,
password : password_login
};
doJSONRequest("GET", "/users/", {}, data, function(location){
document.location = location.location;
})
}
function enable(){
var a = document.getElementById("repeat");
var password = document.getElementById("password");
var repeat = document.getElementById("repeat");
document.getElementById("btnPlaceOrder").disabled = password.value !== repeat.value;
}
function timeout(){
window.setTimeout(function(){
window.location.href = "../../login.html";
}, 600000);
}
And finally the doJSONRequest. This function is in another document but it's function works. I inserted all the function you should needs to be sure. Hope I explained my problem in the right way:
function doJSONRequest(method, url, headers, data, callback){
if(arguments.length != 5) {
throw new Error('Illegal argument count');
}
doRequestChecks(method, true, data);
var r = new XMLHttpRequest();
r.open(method, url, true);
doRequestSetHeaders(r, method, headers);
r.onreadystatechange = function () {
if (r.readyState != 4 || (r.status != 200 && r.status != 201 && r.status != 204)){
return;
}else{
if(isJSON(r.responseText))
callback(JSON.parse(r.responseText));
else
callback();
}
};
var dataToSend = null;
if (!("undefined" == typeof data) && !(data === null))
dataToSend = JSON.stringify(data);
r.send(dataToSend);
}
Thanks for all
It doesn't look like you have any event listeners for your form submission?
If that is the case, then you have your form method set to GET which will pass the request parameters in the url.
Change the form method to POST and the details will go in the request body, rather than as url paramerters:
<form action="/login" method="POST" class="form-signup">

Categories

Resources