Form submits regardless of validation - javascript

I have a form, and I've written a validation script for it, however, it's not working 100%. It outputs errors fine, but the submit button will submit the form, even if it has outputted the alert boxes. Anyone have any idea why?
Apparently not all the code pasted. I would just use the Required parameter, but I need JS validation as it is an assignment. Also, UL is defined before this part of code, as there is a list before this.
HTML:
<div class = "form">
<form name = "contactForm" onsubmit="validateForm()" action = "form.php">
<li><label>First name: </label><input type = "text" name = "fname" autofocus></li><br>
<li><label>Last Name: </label><input type = "text" name = "lname"></li><br>
<li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li><br>
<li><label>Message: </label> <br>
<textarea rows = "10" cols = "50" name = "message"></textarea></li>
<li> <input type = "submit"> </li>
</form>
JavaScript:
function validateForm()
{
var x=document.forms["contactForm"]["fname"].value; //Gets the form and field name from the HTML
if (x==null || x=="") //If the field "fname" contains null, or nothing, then output an alert telling the user to input something into the field. Same goes for the rest of the code.
{
alert("First name must be filled out");
return false;
}
var x=document.forms["contactForm"]["lname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["contactForm"]["email"].value;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(x) == false)
{
alert("Please enter a valid Email");
return false;
}
if (x==null || x=="")
{
alert("Email must be filled out");
return false;
}
var x=document.forms["contactForm"]["message"].value;
if (x==null || x=="")
{
alert("Message must be filled out");
return false;
}
}

You have to trigger event on time of submit. Like this way:
<form onsubmit="validateForm()">

How are you attaching the event listener? I’d wager it’s with:
<form … onsubmit="validateForm()">
You’d need return validateForm(). But wait! Don’t add that.
Your script does not check for valid e-mail addresses correctly. It only checks one error at once. It will annoy users. Use HTML5 validation and back it up with PHP.
By applying type="email", you don’t need a button at all, and mobile users will see an e-mail specific keyboard if available. The browser will validate it, given support.
<input type="email" name="email">
Required fields should use the required attribute.
<input type="text" name="fname" autofocus required>
&vellip;
<input type="text" name="lname" required>
Your labels aren’t correct either; they should surround the element they’re related to, or provide a for attribute matching the element’s id.
You should also validate your HTML. And not put <br>s between <li>s.
Finally, as general [client-side] JavaScript tips:
You don’t have to check the value of a text field for null.
Write !x instead of x == false.

You can also use JQuery to do something like this:
$( "#formId" ).submit(function( event ) {
if($("#nameInput").val() == "")
event.preventDefault();
});
So basically, if nameInput's equals to empty the submit action will be canceled
Take a look at here if you want: https://api.jquery.com/submit/
Good luck

Related

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

Why isnt my javascript function being run?

I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:
<div class = mainInfo>
<?php include "header.php"; ?>
<form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
username: <input type = text name = "userName">
password: <input id= "p1" type = password name = "password">
reenter password: <input id ="p2" type = password name = "passwordConfirmation">
<input type="submit" name =" submitButton" value ="submit">
</form>
<div id="feedback">
</div>
</div>
<script>
function validate()
{
document.getElementById("feedback").innerHTML = "functionbeingcalled";
var p1 = document.getElementById("p1").value,
p2 = document.getElementById("p2").value);
if( ! p1===p2 )
{
document.getElementById("feedback").innerHTML = "passwords dont match";
}
if(p1==="")
{
document.getElementById("feedback").innerHTML = "Must have a password";
}
}
window.setInterval(validate(),1000);
</script>
<?php include "footer.php"; ?>
I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all. This line:
document.getElementById("feedback").innerHTML = "functionbeingcalled";
isn't working either.
Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.
Pass the function instead of calling it.
// no parentheses!
window.setInterval(validate, 1000);
And this is wrong.
if( ! p1===p2 )
it should be this
if( p1!==p2 )
because of the higher precedence of the prefix !
I would suggest that you add listeners on your input fields! ;)
It will then only run the validation code when changes are made. In other words; only when necessary.
It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.
I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution
If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution
Well, you've got several issues...
First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.
You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is: if(p1 !== p2 ), which is how you express "not strictly equal to".
Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:
just before the entire form is submitted
just after the user leaves a form field
as the user is entering data
some combination of all 3
Each of those scenarios is handled through event handlers and a working example of each is shown below.
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");
// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");
var form = document.querySelector("form");
// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
// If validate function returns false, don't submit
if(!validate()){
evt.preventDefault(); // cancel the form submission
feedback.textContent = "Can't submit. Form is not valid!";
}
});
// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");
// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);
// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
input.addEventListener("blur", validate); // Used to validate when user moves off of each element
input.addEventListener("input", validate); // Used to validate as data is being entered
});
function validate() {
// Keep track of whether the form is valid or not. Assume that it is by default
var valid = true;
// .innerHTML is for when you want to assign a string containing
// HTML to a DOM element. This invokes the HTML parser and renders
// the HTML. If you don't have HTML in the string, use .textContent
// instead, which doesn't invoke the HTML parser and is more efficient
// See if the password was typed in both boxes before telling the user
// that the passwords don't match
if(p1.value && p2.value){
// Are they the same?
if(p1.value !== p2.value){
feedback.textContent = "passwords dont match";
valid = false;
} else {
feedback.textContent = "passwords match";
}
} else {
// If both password fields aren't filled in, the form can't be valid
valid = false;
}
if(p1.value === "") {
feedback.textContent = "Must have a password";
valid = false;
}
// Send a result to the caller so it can be known by other code if the form is valid
return valid;
}
<div class = "mainInfo">
<form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
<div>username: <input type="text" name="userName"></div>
<div>password: <input id="p1" type="password" name="password"></div>
<div>reenter password: <input id="p2" type="password" name="passwordConfirmation"></div>
<!-- Any form element that has a "name" attribute will submit its name/value as
part of the form data when the form gets submitted. You probably don't want
the actual submit button to be included in this, so don't give the button
a "name" attribute. -->
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<div id="feedback"></div>
</div>

Form is being submitted in IE11

The below form is being submitted even when its txt_approver is empty.
But it works well in firefox/chrome?
I get no error, what could be the issue?
<script>
function validateForm() {
var x = document.forms["warningnotice"]["txt_approver"].value;
alert(x);
if (x == null || x == "") {
alert("Please enter a name to send a email to ");
return false;
}
}
</script>
<form method="post" action="travel.cfm" id="commentForm" name="warningnotice" onsubmit=" return validateForm()">
<td ><input type="text" name="txt_approver" class="get_empl" required data-error="#errNm35"></td>
<input type="submit" name="Submit" value="Submit" >
</form>
You are using the name attribute to locate the form and the textbox in JavaScript. This is not what the name attribute is for. The id attribute is for this.
Instead of:
document.forms["warningnotice"]
and
<input type="text" name="txt_approver" ...
Those lines should be:
document.forms["commentForm"]
and
<input type="text" name="txt_approver" id="txt_approver"...
And, instead of document.forms, use:
var form = document.getElementById("commentForm");
var tb = document.getElementById("txt_approver");
Also, instead of:
if (x == null || x == "")
You can just use:
if (!String.trim(x))
Because an empty textbox will produce an empty string "" and an empty string, converted to a boolean (which an if statement looks for) will be false, but a populated one, will convert to true.
Lastly, you probably don't want to have your submit button have a name attribute at all because when the form is submitted, the value of the submit button will be submitted along with the other form elements, which probably is not what you want.
The following JS Fiddle shows the code that is working for me in IE 11: https://jsfiddle.net/x0rbnL5s/

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources