Form gets submitted even if validation fails - javascript

I want the username and password to be admin & admin respectively so as to successfully submit the form. But the form gets submitted even if username and password to not match admin & admin.
function validateOnSubmit() {
console.log("Called!");
var isValid = true;
document.getElementById("alert").className = "";
if (document.getElementById("login-password").value.length <= 4) {
isValid = false;
document.getElementById("alert").className = "doWiggle";
setTimeout(function(){
document.getElementById("alert").className = document.getElementById("alert").className.replace('doWiggle', '');
}, 300);
}else
{
if(document.getElementById("login-password").value != "admin" && document.getElementById("username").value != "admin") {
alert("Wrong Password!");
isValid = false;
}
}
console.log(isValid);
return isValid;
}
HTML
<div class="container">
<form action="home.html" id="login-form" method="post" onsubmit="return validateOnSubmit()">
<p class="form-header">Sign In</p>
<span>Username</span>
<br/>
<input type="text" name="username" id="username" autocomplete="off" required/>
<br/>
<br/>
<span>Password</span>
<br/>
<input type="password" name="login-password" id="login-password" onkeyup="return validate()" required/>
<p id="alert">Password should more than 4 characters!</p>
<br/>
<br/>
<input type="checkbox" name="rememberMe" class="rememberMe" id="rememberMe"/>
<label for="rememberMe">Remember Me</label>
<br/>
<br/>
<input type="submit" id="submit" value="Sign In"/>
<br>
<br>
<div id="options">
Not registered ?
</div>
<input type="hidden" name="operation" value="login">
</form>
</div>
<script type="text/javascript" src="js/validate.js"></script>
</body>

The way you need to call the validateOnSubmit() is this way:
<form onsubmit="return validateOnSubmit();">
Notice the return on the onsubmit event. Best guess would you would have forgotten the return keyword, which is not the same and it submits the <form>.
I also see you are using className. It is better to replace it with Element.classList:
element.classList.add(); // Similar to adding class.
element.classList.remove(); // Similar to removing class.
Or if you wanna toggle it, you can use:
element.classList.toggle();
Logic
The logic you have used is wrong:
if (document.getElementById("login-password").value != "admin" && document.getElementById("username").value != "admin") {
The above logic will not work. Use the following:
if (document.getElementById("login-password").value != "admin" || document.getElementById("username").value != "admin") {
It should be || operator here. Currently if any one of the username or password is right, then the form submits, which is wrong.

You need to make sure that you have no js errors. Your js function can be ignored if that happens.
As said above, validateOnSubmit() must be called somehow. The propper way is:
<form onsubmit="return validateOnSubmit();">

Related

Trigger action in form submit javascript html

I am trying to validate the fields in the form and pull up a different html file when the user clicks the submit button if there's no error in field validation.
However, the validators don't seem to work. I want the Event Name and Location fields to alphanumeric characters and spaces, but it seems to take other values as well.
Putting onClick="self.location='successPage.html'" inside the submit button does not seem to validate the fields either. I want it to move to the successPage.html file if all fields in the form are successfully validated.
I don't want to use jQuery.
Here is my code:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
the form element will be passed into the validate function when the user submits, return false to not submit the form, and true to submit it.
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>

How to validate form input text with javascript

I'm trying to create a form with different inputs, input validation error receiving text, it does not validate (I want to be just text). The code is:
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name"><br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname" ><br>
<input type="submit" name="submit" value="Submit">
</form>
The javascript is:
function validateform(){
if(document.checkform.name.value == ""){
window.alert("Please insert your name.");
document.checkform.name.focus();
return false;
}
var nameText = document.forms["myform"]["name"].value; /* here is the problem :-( */
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("Insert just letters !!!");
return false;
}
}
function validateform() {
var nameTxtBx = document.checkform.name,
name = nameTxtBx.value; //<-- added this line
if (name == "") {
alert("Please insert your name.");
nameTxtBx.focus();
return false;
}
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("trebue doar litere");
return false;
}
return true; //<-- added this line
}
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name">
<br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname">
<br>
<input type="submit" name="submit" value="Submit">
</form>
You have typo in your variable, You just rename your variable nameText into name or vice versa.
var nameText = document.forms["myform"]["name"].value;
^^^^^^^
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
^^^^
Named form controls are made members of the form using their name. So even though the form has a name property, because your form also has a control with a name of name, then form.name references the control, not the form's name property.
Similarly, having a control with a name of submit means that you can't call the form's submit method, because form.submit references the control, not the method. So you should use control names that don't clash with standard form properties. Also, it's rare to require an ID for form controls since they can be referenced as properties of the form.
Lastly, it is handy to pass a reference to the form from the listener using this, then you don't need an ID on the form either. Consider:
<form onsubmit="return validateform(this)" ... >
Name: <input type="text" name="firstName"><br>
Surname: <input type="text" name="surname"><br>
<input type="submit" value="Submit">
</form>
Then in the function:
function validateform(form) {
Get the value of the firstName control once:
var firstName = form.firstName.value;
Now do the tests:
if (firstName == "") {
window.alert("Please insert your first name.");
form.firstName.focus();
return false;
}
It's more appropriate to use test than match if you want to test for a pattern rather than find all the matches:
if (!/^\s*[A-Za-z]+\s*$/.test(firstName)) {
alert("Insert just letters !!!");
return false;
}
}

Comparing form input values

I know there are a few threads on this topic, and in fact I got my code from one such thread, but I just can't seem to get it to run. I'm trying to compare two input boxes in an HTML form using javascript.
Here is my JS:
<script>
function checkform(form1)
{
if(form1.password.value != form1.passwordConfirm.value)
{
alert("Passwords must be the same");
form1.password.focus();
return true;
} else {return false;}
}
</script>
Here is the HTML:
<!Doctype html>
<script type="C:/wamp/www/Table/" src="javascript.js"></script>
<form name="form1" action="demo_form.asp">
Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password cannot be empty')">
<input type="submit" value="Submit" onClick="return checkform(form1);">
</form>
</html>
Any help would be awesome!
Thanks
Mike
You'll need to assign an id to your form, and get that.
Replace:
<form name="form1" action="demo_form.asp">
With:
<form name="form1" action="demo_form.asp" id="myForm">
And and this:
function checkform(form1){
With this:
function checkform(){
var form1 = document.getElementById('myForm')
You also need to switch your return statements, to return false when the PW's don't match.
The resulting JS / HTML:
function checkform(){
var form1 = document.getElementById('myForm');
if(form1.password.value != form1.passwordConfirm.value)
{
alert("Passwords must be the same");
form1.password.focus();
return false;
}
return true;
}
<form name="form1" action="demo_form.asp" id="myForm">
Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password cannot be empty')">
<input type="submit" value="Submit" onClick="return checkform();">
</form>
Notice how I removed the else around the second return statement. It's not needed.
Take out return from the onclick.
onClick="checkform(form1);"

HTML button onClick listener calling HTML form onSubmit javascript function

I am a novice in web development, I have created a simple html page. The page has two buttons, Submit and Display Data. The Submit button is supposed to post form data to a particular page after validating the form. This button is working fine. I am facing a problem with the Display Data button. The button is supposed to open a separate page and there should not be any kind of form validation. The page is getting open but the form is also getting validated.
The html page:
<html>
<head>
<script>
function validateForm()
{
var name=document.forms["myForm"]["name"].value;
var email=document.forms["myForm"]["email"].value;
var mobile=document.forms["myForm"]["mobile"].value;
var address=document.forms["myForm"]["address"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (name==null || name=="")
{
alert("Name must be filled out");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
else if(isNaN(mobile)||mobile.indexOf(" ")!=-1)
{
alert("Enter numeric value")
return false;
}
else if (mobile.length != 10)
{
alert("Enter 10 digit mobile");
return false;
}
else if (mobile.charAt(0)=="0")
{
alert("Mobile no should not start with 0");
return false;
}
else if (address==null || address=="")
{
alert("Address must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>Employee Details Entry</h2>
<form name="myForm" action="insertDisplay.php" onSubmit="return validateForm()" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" value="Submit"> <button onClick="location.href = 'insertDisplay.php'">Display Data</button>
</form>
</body>
</html>
Where am I going wrong? Why is the form validation function getting called?
place
<button onClick="location.href = 'insertDisplay.php'">Display Data</button> this line out of the form...
give this button the type you want to behave it.
<button type="button" onClick="location.href = 'insertDisplay.php'">Display Data</button>
You can take the values out of the form, or you can use, <input type="button"/> tag. It will not submit your form and will work as you intended.
<input type="button" value="display data" onClick="location.href = 'a.php'">
I suppose you also want your datas to be passed to your PHP file after clicking your button ?
If you push the out of the form will not be sended and you'll have no datas.
In fact, you want both buttons to submit your form, but only the first one should validate it ?
If this is it you can do this :
<form name="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" name="typesubmit" value="Submit" onclick="return validateForm();" />
<input type="submit" name="typesubmit" value="Display Data" />
</form>
You'll be abled on your insert.php file to make difference between display and submit by checking $_POST['typesubmit'] value.
And if you want your "display" button to post your form on another php file, you can do this :
<form name="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" value="Submit" onclick="return validateForm();" />
<input type="submit" value="Display Data" onclick="document.myForm.action='display.php';" />
</form>

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources