HTML Form using Javascript did not verify instead changed the link - javascript

Code:
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
function generateUserPassword(){
var passwordArray = [];
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
function loginUsingPassword(inputPassword){
for (int i; i<passwordArray.length; i++){
if (inputPassword=passwordArray[i]){
document.cookie="reportLogged=true;";
window.location.href="http://tool-box.weebly.com/report.html";
}
}
}
</script>
Result:
Input : 198237645
Output : The link changed to http://tool-box.weebly.com/report-login.html?loginPassword=198237645
What is the solution?

I am not quite sure of your requirement, but there are some points might be helpful for you,
Generally we use method post for such form submission, rather than the default one(get).
So you might want to to change the follow code
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
to the follow one
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;" method="post">
After you do the above change, the password will not be displayed in the URL as you mentioned, to avoid security issue.
By reading your code, I assume you would like to check whether the password inputed by user is the same as a list of predefined password in your code.
But you have the follow code there
if (inputPassword=passwordArray[i]){//This is a common bug to mistake === to = in if
If you would like to compare the variable inputPassword and your predefined passwords(passwordArray), you should use == or === rather than the assignment operation(=), so the code should be
if (inputPassword === passwordArray[i]){
Hope the above hints could help you on debug your code.
Here is a working version based on my understanding to your requirement, but actually you didn't specify your requirement...
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(document.forms['myForm']['loginPassword'].value);return false;" method="post" name="myForm">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
var passwordArray = [];
function generateUserPassword(){
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
}
function loginUsingPassword(inputPassword) {
generateUserPassword();
var passwordCorrect = false;
for (i = 0; i< passwordArray.length; i++){
if (inputPassword === passwordArray[i]){
document.cookie="reportLogged=true;";
passwordCorrect = true;
window.location.href="http://tool-box.weebly.com/report.html";
}
}
if (passwordCorrect !== true){
alert("Wrong Password!");
return false;
}
}
</script>

Your form tag has no method attribute, so it defaults to GET. It has no action attribute, so it defaults to the page you're on. If you submit the form, it encodes the submitted values in the URL (how GET is designed to work) and you land on the same page. This is exactly the behavior you have specified.

Related

Javascript form validation return false error

I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.

Want both PHP & JS form (empty fields/password match) validation?

I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.

Check if html form values are empty using Javascript

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.

Validating form data in Javascript xhtml 1.0 strict, not considering server side scripts for this instance

There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>

validation not working for js

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" onClick="javaScript:validate();" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.

Categories