I am using javascript to validate a web form for submission to a database, I have coded the form and the validation, but it does not seem to work.
When the form is completed and it is valid it is meant to go to a success page in a separate HTML file, but if it is not valid, the text on the form turns red, a message box pops up and alerts the user that it is invalid. On Chrome and IE, it seems to display the error but go to the success page anyway. The Message Box does not come up either, i only see the text turning red before it goes to the success page.
I wanted to know how to fix this. I have searched on the Internet but found no solution.
I have a function called validateForm(), which is a series of if statements checking the if the fields are valid, and if they are not, a variable called 'result' is set to false, at the end, it sends the alert message and returns the variable 'result'.
The code for my submit button is here:
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
The Success Page is set in the form code as an 'action'.
Here is my Validate Form :
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value==""){
msg+="You must enter your Name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(document.ExamEntry.subject.value==""){
msg+="You must enter the Subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value=="")
{
msg+="You must enter the Examination Number \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value.length!=4)
{
msg+="Your Examination Number must be 4 characters long \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
var lvlmsg="";
for(var i=0; i < document.ExamEntry.level.length; i++)
{
if(document.ExamEntry.level[i].checked)
{
lvlmsg = document.ExamEntry.level[i].value;
break;
}
}
if(lvlmsg=="")
{
msg+="You Must Indicate Your Level";
result=false;
document.getElementById('radioButtons').style.color="red";
}
else
{
alert(lvlmsg);
}
if(msg==""){
return result;
}
else{
alert(msg);
return result;
}
}
I created a form without the radio buttons and changed the function call.
I think the mistake is here:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" />
<input type="text" id="subject" name="subject" />
<input type="text" id="examnumber" name="examNumber" />
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
I changed the function call to onsubmit (because I think it's better practice) and return validateForm() to simply validateForm(). Why would you want the return statement? Doesn't make sense to me.
http://jsfiddle.net/rcsole/cqy7q/
Related
The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".
I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.
The code snippet is attached. The function name in html is called validate();
ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.
function Validate() {
alert(document.getElementsByName("UserInfo")[0].value);
if (name == "" || name == null) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" />
</div>
</fieldset>
You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.
Below is the working model of your snippet.
I had assigned the input value to value and check for existence, do alert if not a valid input.
function Validate(){
const value = document.getElementsByName("UserInfo")[0].value;
if(!value) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<form onsubmit="Validate()">
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" required />
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
UPDATE:
Use required attribute.
Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.
Adding required will abort the submit itself.
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.
I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>
With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.
Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.
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>
My form is working fine in Firefox and IE. On calling onsubmit it calls js function and validates the code, and if validation is good, then it submits the form.
However, in chrome it is not doing validation, but simply submitting the form directly.
I am not sure why it is so, Did lot of search but in vain.
Any help will be great towards solving this issue.
Form Code:
<form name="myform" action="queryfeedback.php" method="post" onSubmit="return validateForm(myform);">
<label for="labelField_Name" id="idLabel_Name"></label>
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
<br />
<label for="labelField_EMail" id="idLabel_EMail"></label>
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
<br />
<label for="labelField_Message" id="idLabel_Message"></label>
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
<br />
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</form>
Validation Code:
function validateForm(form)
{
alert(form.nameField_Name.value);
//alert(formValueEMail.value);
//alert(formValueMessage.value);
if(form.nameField_Name.value=='')
{
alert("Name field is required. Please fill it in.");
form.nameField_Name.focus();
form.nameField_Name.select();
return false;
}
if(form.nameField_Name.value=='Enter your name here')
{
alert("Name field is required. Please fill it in.");
form.nameField_Name.focus();
form.nameField_Name.select();
return false;
}
if(form.nameField_EMail.value=='')
{
alert("E-Mail Address field is required. Please fill it in.");
form.nameField_EMail.focus();
form.nameField_EMail.select();
return false;
}
if(form.nameField_EMail.value=='Enter your E-Mail address here')
{
alert("E-Mail Address field is required. Please fill it in.");
form.nameField_EMail.focus();
form.nameField_EMail.select();
return false;
}
//Checking for correct format of EMail address.
var x=document.forms["myform"]["nameField_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;
}
if(form.nameField_Message.value=='')
{
alert("Message field is required. Please fill it in.");
form.nameField_Message.focus();
form.nameField_Message.select();
return false;
}
if(form.nameField_Message.value=='Enter your message for us here')
{
alert("Message field is required. Please fill it in.");
form.nameField_Message.focus();
form.nameField_Message.select();
return false;
}
return true;
Try passing in the event parameter and running event.preventDefault() so it stops submitting the form until it is validated.
You aren't closing your function 'validateForm' with }. Therefore it could be throwing an error.
Use onsubmit="return validateForm(this);" Note that attribute name is onsubmit with no camel case and argument is this
validateForm should be a global function.
working example: http://jsfiddle.net/qrZ8a/3/