Form submitting with errors - 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>
<li><label>Last Name: </label><input type = "text" name = "lname"></li>
<li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li>
<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;
}
}

Simply change your html:
<form name = "contactForm" onsubmit="return validateForm()" action = "form.php">
You have to add keyword return before your ValidateForm() function.

You don't have anything telling it NOT to submit the form. The "return false" just sends the message back. You need to get rid of that OnSubmit tag, and call the function from onClick from your Submit button. Then only if it returns TRUE, do the form submit.

Related

html javascript doesn't work or show an alert

i'm using javascript to validate my html (checking if the user input a correct data ) source code and it's more than simple but the problem is that when i press the submit button i can't see any result or alert
<script type= "text/javascript">
function checkname()
{
name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
return name.value("Welcome" + name + " to valet parking service VPS");
}
</script>
that's all for the first part where the script is written now in the html tag where the button is typed
<input type="submit" value=" submit " >
and that's what written in the form
<form onsubmit = " checkname(); return false; ">
This is the mistake (you always return false to the submit function):
<form onsubmit = " checkname(); return false; ">
Try this:
<form onsubmit="return checkname();">
Then modify your checkname function to something like this:
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
name.value("Welcome" + name + " to valet parking service VPS");
return true;
}
Here is the JSFiddle: http://jsfiddle.net/267wL/
HTML
<form action="demo.html" id="myForm" onsubmit = "checkname(); return false; " method="post">
<p>
<label>First name:</label>
<input type="text" id="myname" />
</p>
<input type="submit" value=" submit "/>
</form>
JavaScript
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/;
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
name.value = "Welcome " + name.value + " to valet parking service VPS";
return false;
}
You don't have to check null values. If the name.value is empty, your regex validation failed.
Pay also attention that the welcome message is set in the input text. Weird behaviour...
The return true; will block all following code.
Try This
<script> function checkname() {
var x = document.forms["myForm"]["myname"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
<form name='myForm' action='action.php' onsubmit='return checkname()' method='post'>
First name: <input type="text" name="myname"><input type="submit" value="Submit"></form>

Javascript - Executing all the validation functions on form submit

I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}
Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.
validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.

How to check checkbox array along with text using javascript

I have HTML page with javascript. In this, I have form which contains text for name and checkboxes. Below is the HTML form:
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="dname">
<pre>
<input type="checkbox" name="drug" value="id1">ID1 <input type="checkbox" name="drug" value="id2">ID2</br>
<input type="checkbox" name="drug" value="id3">ID3 <input type="checkbox" name="drug" value="id4">ID4</br>
</pre>
<input type="submit" value="Submit">
</form>
Below is the javascript for same:
<script>
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
//var y=document.drugForm.drug[0].value;
var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
alert("click any checkbox "+ y);
//alert("Working with boolean " + y);
return false;
}
}
</script>
Here, I want to check whether any checkbox is checked also along with name entry. But whenever I am trying to put for loop with y (array) in else if condition or anywhere in function, the code is not working and instead giving action directly.
My question, specifically, is how to check checkboxes, like did in if condition, is checked and how to get those values?
The code below validate when there's at least one checked box:
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for (k=0;k<y.length;k++) {
if(y[k].checked) {
return true;
}
}
alert("Check one option at least");
return false;
}
}
There's another goog option in jquery as shown in another post.
Try this,
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (x)
{
if(!$('input:checkbox:checked').length)//check length of checked checkboxes
{
alert("click any checkbox ");
return false;
}
}
}

How to stop HTML to insert data into database when wrong input taken

So I have my form here
<form name = "reservation" method = "post" action = "makereservation.php" autocomplete="off">
(my codes here)
<input type = "submit" value = "Submit" onclick="checkPhoneNumber(document.reservation.contact)">
</form>
And my Javascript function here to detect wrong length of phone number
function checkPhoneNumber(contact)
{
var phoneno = /^\d{10}$/;
if(contact.value.match(phoneno))
{
return true;
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
What I want to ask is that how do I stop from inserting into database when the input for phone number is wrong?
What I got now is that it detects wrong length of phone number but it still insert into database.
Try this
<form name = "reservation" method = "post" action = "makereservation.php" autocomplete="off"
onsubmit="return checkPhoneNumber(document.reservation.contact)">
<input type = "submit" value = "Submit" >

How to validate 3 fields in javascript

I want to validate 3 fileds
First name text box
Last name text box
Middle name text box
here is my code:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["lname"].value;
var z=document.forms["myForm"]["mname"].value;
if(((x!='') && (y=='' && z==''))
|| ((y!='') && (x=='' && z==''))
|| ((z!='') && (x=='' && y=='')))
{
alert("First name must be filled out");
return false;
}
alert("fill input filed");
return false;
}
</script>
My code is executing like this: if i wont enter anything in any field - alerting, this part is fine. Then when i enter one of the field its alerting me the if part same way if i will enter two text box my if part should be executed, but its not happening.
Can you change that condition please so that if I will fill 2 fields it should alert me at least one field can be filled?
Make it simple, your first name is mandatory, so make it first priority
if(x==''){
alert("First name must be filled out");return false;
if(y=='' && z==''){
//alert();// other condtions
}
}else{
alert("fill input filed");return false;
}
I think this is what you are looking for...
Javascript Code
<script type="text/javascript">
function validateForm()
{
var x=document.getElementById("fname").value;
var y=document.getElementById("mname").value;
var z=document.getElementById("lname").value;
if((x==''))
{
alert("First name must be filled out");
return false;
}
else if((y==''))
{
alert("Middle name is empty");
return false;
}
else if((z==''))
{
alert("Last name is empty");
return false;
}
return true;
}
</script>
HTML Code
<form action="#">
<input type ="text" id ="fname"></input>
<input type ="text" id ="mname"></input>
<input type ="text" id ="lname"></input>
<input type="submit" onclick="return validateForm();">
</form>

Categories