For some reason, this code always redirects to education.php regardless of whether or not the fields are blank. I want to verify the fields have values in them, but for some reason they keep redirecting but not writing anything in the database. Any help would be greatly appreciated.
<body>
<form action="education.php" method="post" onsubmit="return validate_fields()">
<div style="text-align: right">
<ul>
First Name: <input id="first_name" name="first_name" size=25/> <br>
Last Name: <input id="last_name" name="last_name" size=25/> <br>
Email: <input id="emailaddress" name="emailaddress" size=25/> <br>
Password: <input id="user_password" name="user_password" type="password" size=25/> <br>
<center><input type="submit" name="submit" id="submit" value="Register Now"/></center>
</ul>
</div>
</form>
<script type="text/javascript">
function validate_fields()
{
var first_name = document.getElementByID("first_name").value;
var last_name = document.getElementById("last_name").value;
alert(""+first_name+" "+last_name);
if (first_name.length < 1 || last_name.length < 1)
{
alert("Please fill in your name.");
return false;
}
var email = document.getElementById("emailaddress").value;
if (email.length < 1)
{
alert("Please fill in your email address.");
return false;
}
var password = document.getElementById("password").value;
if (email.length < 1)
{
alert("Please put in a password.");
return false;
}
alert(first_name+" "+last_name+" "+email);
return false; //was true, changed to see if still redirects.
}
</script>
</body>
You've got a typo on the first line of your function so it isn't returning false (or true), it is just not running at all. This explains both why you don't get any of the alerts and why the form submit goes ahead.
var first_name = document.getElementByID("first_name").value;
// you need a lowercase "d" here ------^
It should be .getElementById(), not .getElementByID().
This is the sort of thing you can easily find for yourself with the appropriate developer tools for your browser. Chrome has this built in (just press ctrl-shift-J to bring up dev tools), or you can add Firebug for FireFox, and IE has had a dev toolbar option for several versions now.
You have a typo here:
var first_name = document.getElementById("first_name").value;
You wrote ByID it sould be ById!
Related
I am validating a login form. My password field is working perfectly as I want but while validating USERNAME field I'm calling ajax for username validation i.e to check if username exists and after that if username field is empty calling a js function which shows a message but here I'm having a popup message but I wanted to display that message above the textbox. How can i do that?
Thanks in advance. :)
Add an error holder before the input box.
<span style="display:none;color:#E84344;" id='USERNAME_ERROR'> </span>
<input type="text" name="USERNAME" id="USERNAME" class="form-control input-lg" placeholder="Email or User Name" onchange="CheckLoginCustomer('loginform')"/>
Following Change you need to do in loginvalidation function
function loginvalidation(formname)
{
var form=document[formname];
var USERNAME= form.USERNAME.value;
var PASSWORD= form.PASSWORD.value;
var userNameFlag = form.userNameFlag.value;
if(USERNAME == '')
{
document.getElementById('USERNAME_ERROR').innerHTML = 'Please Enter Registered UserId';
document.getElementById('USERNAME_ERROR').style.display = 'block';
return false;
}
.....
.....
Whereever you dont want to show this error message do the following:
document.getElementById('USERNAME_ERROR').innerHTML = '';
document.getElementById('USERNAME_ERROR').style.display = 'none';
Do the same for others ..
i'm making a code for you please check below link:
https://jsfiddle.net/fatehjagdeo/9way7qc2/1/
or check my code below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form>
<input type="text" id="username"><br>
<input type="password" id="password"><br>
<input type="button" value="submit" id="submit">
</form>
<script>
$(document).on('click','#submit',function(){
$('.error').remove();
var username=$('#username').val();
var password=$('#password').val();
var err=0;
if(username==""){
$('#username').before('<p class="error">Please enter username</p>');
err=1;
}
if(password==""){
$('#password').before('<p class="error">Please enter password</p>');
err=1;
}
if(err==0){
// send your ajax here
}
});
</script>
(edit: code updated)
I am running into an error, when trying to clientside-validate with JavaScript that the user has filled in the forms correctly in the Register part of my HTML form.
The HTML and JS file are pretty straightforward:
(Fiddle)
JavaScript and HTML:
function validateForm() {
var name = document.getElementById('username').value;
var email = document.getElementById('email').value;
if (name == null || name == "" || checkIfSpaceOnly(name) == false) {
return false;
}
else if (email == null || email == "" || validateEmail(email) == false){
return false;
}
else
return true;
}
//other methods used in validateForm:
function checkIfSpaceOnly(input) {
var re = /\S/;
return re.test(input);
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
window.onload = function()
{
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener("click", validateForm);
}
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="design.css">
</head>
<div class = "body1">
<div class = "forms" id="forms">
<h2>Log in</h2>
<form name='loginform' action='login.php' method='POST'>
<input type='email' name='email' placeholder="Email" ><br>
<input type='password' name='password' placeholder="Password" ><br><br>
<input type='submit' value='Log in'><br><br>
</form>
<hr>
<br><h2>Register</h2>
<form onsubmit="" name="register" action="register.php" method="POST" onsubmit="return validateForm()">
<input type="text" name="username" class="form-control" placeholder="Username" id="username"><br>
<input type="email" name="email" class="form-control" placeholder="Email" id="email"/><br>
<input type="password" name="password" class="form-control" placeholder="Passwoord"><br>
<br>
<input type="submit" name="submit" id="submit" value="Create user">
</form>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</html>
So the problem is, it's like the JS file isn't used at all by the HTML file. The form gladly registers any user, no matter if they fulfill the JavaScript file's if conditions or not.
I checked the console, and it says (when the user has been registered), "ReferenceError: validateForm is not defined".
Except checking that the file directories are correct of course, I have searched and read about both general HTML JS form validation Errors, 20-something "similar question" on here, and that specific ReferenceError. I've changed values, names, moved code parts around.... but I can't seem to find the problem and don't know what to do, although it feels like it's just a simple mistake somewhere in the code.
You have 3 problems
Your fiddle is setup incorrectly; all the code is wrapped in an onload which means your validateForm method is not accessible from HTML markup
You have 2 onsubmit attributes in the form - the second contains what it should contain but is being ignored because of the first
You assign the event handler both in markup and in code. Choose one, stick with it.
When you fix these 3 problems, it works as expected and does not submit the form if anything goes wrong (ie, false is returned from validateForm)
https://jsfiddle.net/spwx1rfd/7/
Please check the if condition, you have made a mistake.
Wrong code
if (uName == "") || checkIfSpaceOnly(uName) == false) {
return false;
}
Right code
if (uName == "" || checkIfSpaceOnly(uName) == false) {
return false;
}
I am trying to validate 3 form inputs and based on this I want to display either a success page or a failure page. I must do this using JavaScript. I have this so far:
<script src="scripts/formvalidator.js"></script>
<form method = "post" onsubmit = "validateForm()" >
<label><strong>Name:</strong></label>
<br>
<input type="text" name="name" id="name" placeholder="Enter first and last name" />
<br>
<br>
<label><strong>Email:</strong></label>
<br>
<input type="email" name="usremail" placeholder="hello#wavemedia.ie" />
<br>
<br>
<!-- comment box -->
<legend><strong>Your Message</strong></legend>
<textarea name="comments" id="comments" rows="10" cols="50">
</textarea>
<div id="buttons">
<!-- buttons -->
<input type="submit" name="submit" id="submit" value="Send" style="margin-left:100px;">
<input type="reset" name="reset" id="reset" value="Reset" style="margin-left:20px;">
</div>
</form>
My JavaScript file:
// JavaScript Document
//form validation
function validateForm() {
//name check
var name = document.getElementById("name").value;
var nameLength = name.length; //get length of string stored in name
//email - ref http://www.w3schools.com/js/js_form_validation.asp
var email = document.getElementById("usremail").value;
var atpos = email.indexOf("#"); //gets position of the # symbol in the string
var dotpos = email.lastIndexOf("."); //gets position of the last dot in the string
//message - same method as name validation
var message = document.getElementById("comments").value;
var messageLength = message.length;
if (name.length < 3)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (atpos < 1 || dotpos<atpos+2 || dotpos+ 2 >= email.length)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (messageLength < 20)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else {
return true;
}
}
The problem is when I run the code and submit the form - no matter what I input - nothing happens.
You have defined a function but I cannot see that you are calling it anywhere. You need to call it by changing the corresponding HTML code to this:
<input type="submit" name="submit" id="submit" value="Send" onclick="validateForm()" style="margin-left:100px;">
First, add onClick="function();" to your code.
If you want to get data by name, use getElementsByName("tagname");
Note that the function returns an array. (Because you can add many inputs with the same name, that's why there's Elements).
Working Fiddle [http://jsfiddle.net/pdp44fx4/2/][1]
I couldn't paste it as a link, sorry.
I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing to submit, but usually my form just ignores codes and submits anyway.
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else {
return true;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
You're making it to complex.
JavaScript:
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else { return true; }
}
HTML:
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
Your validation works fine, but because you are trying to
document.getElementByID("JSError").innerHTML
instead of
document.getElementById("JSError").innerHTML
JS throws an error and never reaches your "return false".
You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).
Example fiddle: http://jsfiddle.net/6tFcw/
1st solution - using input[type=submit]
<!-- HTML -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
// JavaScript
function validateForm(){
var target = document.getElementById("name"); // for instance
if(target.value.length === 0){
alert("Name is required");
return false;
}
// all right; submit the form
return true;
}
2nd solution - using input[type=button]
<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />
// JavaScript
window.onload = function(){
var target = document.getElementById("name");
document.getElementById("submit").onclick = function(){
if(target.value.length === 0){
alert("Name is required");
}else{
// all right; submit the form
form.submit();
}
};
};
I have a subscription form on my website that I am trying to validate. When the user clicks the button signup the function validate() is called and the fields should get validated however im not getting it to work.
Obviously there are some errors in my code. I have tried to fix it with the little knowledge I have, but can't get it to work. I would greatly appreciate it if you could point me into the right directions as to what I am doing wrong.
Code follows:
function validate()
{
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var nat = document.getElementById("nat").value;
var address = document.getElementById("address").value;
var town = document.getElementById("town").value;
var zip = document.getElementById("zip").value;
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var password2= document.getElentById("password2").value;
if (name == "" )
{
window.alert("Please Enter your Full Name")
}
checkNr= isNaN(phone)
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
if (nat == "")
{
window.alert("Please enter your nationality")
}
if (address == "")
{
window.alert("Please Enter your address")
}
if (password != password2)
{
window.alert("Your passwords did not match. Please re-enter")
}
}
</script>
HTML:
<form name="subscribe">
FULLNAME: </strong><input type="text" id="name"/><br />
PHONE NR: <input type="text" id="phone" onblur="validateForm()" /><br />
NATIONALITY:<input type="text" id="nat" /><br />
Address:<input type="text" id="address" /><br />
Town:<input type="text" id="town" /><br />
Zip Code: <input type="text" id="zip" /><br />
Username: <input type="text" id="userName" /><br />
Password:<input type="password" name="password" /><br />
Retype:<input type="password" name="password2" /><br />
<input type="button" value="submit" onclick="validate()" />
</form>
I found these mistakes in your code:
there is no validateForm() function specified in your phone input field
if you want your form to send data, set the type submit, not button on your submit button
if you want to stop the form submitting when something is not filled, hook the onsubmit event of the form:
<form onsubmit="return validate()"> ... // note the return keyword
and the script
function validate() {
...
if(somethingIsWrong) return false; // false stops submitting
else return true; // do submit
}
also note the getElentById typo mentioned by #FranciscoAfonzo
I found my mistake. It looks like you can not use the document.get with a password input field. I took out the password and it worked. It would be great if I could get some input from someone more experience as to why.
A couple of suggestions:
In JavaScript comparisions are done using === (equal to) and !== (not equal to).
If you have only the variable name in the if loop that will also suffice.
Like:
if (address)
{
window.alert("Please enter your address")
}