Javascript text field validation - javascript

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;

You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}

document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>

Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.

Related

Trying to validate username and password in javascript but not getting alert and desired output

please check the code
function validate() {
var name = document.getElementById("name");
var pwd = document.getElementById("pwd");
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name === null || name === "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
There's a much easier way to do what you are trying to do. You can use the native properties of form to your advantage:
<form>
Username: <input type="text" minlength="2" required>
<br> Password: <input type="password" minlength="6" required>
<br>
<button type="submit">Submit</button>
</form>
HTML elements should be before javascript, like this:
<!DOCTYPE html>
<html>
<body>
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</body>
</html>
You haven't provided the full code, so we can't really help you. As far as i can see you didn't make the alert for succesful validation.
You need to get the value, so you need to add .value to the getElement functions.

Disable Button for form

I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>

Why am i getting " Uncaught TypeError: Cannot read property 'addEventListener' of undefined"

I can't figure out why i am getting this error: "Uncaught TypeError: Cannot read property 'addEventListener' of undefined "
Here is the code:
HTMl
<form method="post" action="" id="security-check">
<input type="text" name ="first" placeholder="First Name">
<input type="text" name ="last" placeholder="Last Name">
<input type="number" name ="dob" placeholder="DOB">
<input type="text" name ="state" placeholder="State">
<input type="submit" value="submit">
</form>
JavaScript
var input = document.getElementsByTagName('input');
var fname = input[0];
var lname = input[1];
var dob = input[2];
var rez = input[3];
function idCheck(first, last, date, state){
this.first = "Teddy";
this.last = "Broosevelt";
this.date = 03041894;
this.state = "NY";
if(firstName != this.first){return false;};
if(lastName != this.last ){return false;};
if(birthDate != this.date){return false;};
if(rez != this.state){return false;};
}
input[4].addEventListener('submit', function(e){
idCheck(fname, lname, dob, rez);
e.preventDefault();
}, false);
Cannot read property addEventListener of undefined simply means that your attempt to use the addEventListener method of some object can't work because the object that you are trying it on isn't really an object it's "undefined".
So, input[4] is the object qualifier you have before addEventListener, so input[4] is what is undefined. You must examine your code to determine why that is. As others have said, you most likely don't have a 5th element being returned to your input nodelist varaible.
EDIT:
Now that you've posted more of your code, there are many problems. The biggest of which is that you are wiring up your event handler incorrectly so it will never get called. See my updates to your code and comments below:
<html>
<head>
</head>
<body>
<!-- Don't use hypens in element ids -->
<form method="post" action="#" id="securityCheck">
<input type="text" name="first" placeholder="First Name">
<input type="text" name="last" placeholder="Last Name">
<input type="number" name="dob" placeholder="DOB">
<input type="text" name="state" placeholder="State">
<input type="submit" value="submit">
</form>
<script>
// If you wish to work with form events, you need a reference to your form:
var form = document.getElementById("securityCheck");
var input = document.getElementsByTagName('input');
var fname = input[0];
var lname = input[1];
var dob = input[2];
var rez = input[3];
function idCheck(first, last, date, state) {
this.first = "Teddy";
this.last = "Broosevelt";
// This should be a date. You had it as a number and that
// number could be interpreted as an octal because it starts with 0
this.date = new Date(1894, 2, 4); // Month is zero-based
this.state = "NY";
// Where are firstName, lastName and birthDate being declared?
if (fName != this.first) { return false; };
if (lName != this.last) { return false; };
if (dob != this.date) { return false; };
if (rez != this.state) { return false; };
}
// You are attempting to wire up a submit button to the submit
// event, but a submit button does not have this event, the form does
form.addEventListener('submit', function (e) {
// Calling idCheck may result in a return value of false
// or it may result in nothing of consequence happening
// Either way, you are not doing anything with what may
// or may not come back from idCheck. All this function really
// does is ensure that the form never submits
idCheck(fname, lname, dob, rez);
e.preventDefault();
}, false);
</script>
</body>
</html>

TypeError: document.getElementById(...); is null in Javascript

All of my var statements uses identifiers:
var identifier = document.getElementById("somename");
So why am I getting a null error?
I ran this code in the Javascript runner and got the null error message. And in my browsers Firefox and Chrome I don't get any errors or warnings. When I run the code in the browser and click the button to activate the event handler, the form clears. It's not going to a server anyway. It's just practice. I'm taking a course in javascript and Dynamic HTML. If anybody care to look at my code and tell me what I'm doing wrong I'd appreciate it.
There's got to be something that I'm not getting right. Here is the script:
window.onload = function(){
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
if(document.getElementById("uname").value == ""){
return false;
alert("Your user name can't be blank.");
};
if(pass1.value !== pass2.value){
get.documentElementById("signin").value.disabled = true;
return false;
alert("Please retype your password.");
}else if(pass1.value === pass2.value){
alert("Welcome!");
};
};
HTML
<body>
<form action = "" name = "form" method = "Post">
<label for="fname">First Name:</label><input type = "text" id = "fname"required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type = "text" id = "uname" required></input><br/>
<label for="password1">Password:</label><input type = "password" id = "password1"required ></input><br/>
<label for="password2">Verify Password:</label><input type = "password" id = "password2"required ></input><br/>
<label for="email">Email Address:</label><input type = "email" id = "email" required></input><br/>
<button type = "submit"id = "signin" onclick = "function()">Submit</button>
</form>
<script src="signUp.js"></script>
</body>
I cleaned up your code for you. There were several spots where you had errors (e.g., typing pass1.value instead of just pass1. This should work, but of course take time to study it to see what I changed and understand why. Here's a fiddle showing it working. Note that you should never expect this type of code to run in the "runners" that you've made reference to; the code here makes explicit reference to particular elements in the DOM, which the runners won't have. (Using a site like JSFiddle is better for this sort of thing, since you can put HTML into it as well).
var submitForm = function () {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
console.log(pass1, pass2);
if (document.getElementById("uname").value == "") {
alert("Your user name can't be blank.");
return false;
}
if (pass1 !== pass2) {
document.getElementById("signin").value.disabled = true;
alert("Please retype your password.");
return false;
} else if (pass1 === pass2) {
alert("Welcome!");
}
};
<body>
<form action="" name="form" method="POST">
<label for="fname">First Name:</label><input type ="text" id = "fname" required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type ="text" id ="uname" required></input><br/>
<label for="password1">Password:</label><input type="password" id="password1" required></input><br/>
<label for="password2">Verify Password:</label><input type="password" id="password2" required ></input><br/>
<label for="email">Email Address:</label><input type="email" id="email" required></input><br/>
<button type="submit" id="signin" onclick="submitForm()">Submit</button>
</form>
</body>

Form validation !='' in if statement?

Can anyone tell me whats wrong with this code, im validating a form making sure all the fields have text in them before anyone can submit. everything works until i put in the !='' var. I am sure the id's are correct
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script language="javascript">
$(document).ready(function() {
// declare the flags outside the other functions
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready && emailvalue!='' && usernamevalue!='' && firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
}
else {$("#register").prop('disabled',true);}
}
and here is my form code so you can see if thats the issue...
<p>First Name: <input id="first" type="text" name="name" maxlength="100"> </p>
<p>Last Name: <input id="last" type="text" name="name" maxlength="100"> </p>
<p> Email: <input type="text" name="email" id="email" maxlength="100" />
<span id="box" style="display:none"></span></p>
User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
<span id="msgbox" style="display:none"></span>
<p> Password: <input id="password" type="password" name="password"> </p>
You spelt your variable name firstvalue incorrectly:
firstvale!=''
Edit
Move these 5 lines:
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
From where they are to right under function checkSubmitStatus(){ and above your big if statement.
Where they are now, they are only assigned once, to the value of the form when the page first loads which I'm assuming at least one of them is empty.
You need to move those lines into your checkSubmitStatus() function so that they get updated whenever the function is called. The final result should look like:
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready &&
emailvalue!='' && usernamevalue!='' &&
firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
} else {
$("#register").prop('disabled',true);
}
}
Judging from your code, I get the feeling that it's copy-pasted together from different parts of your code. What might be happening is that emailvalue, usernamevalue etc are really out of scope at the time the checkSubmitStatus is called. I might also be wrong, but it's hard to tell more based on the provided code, since it seems to be alright.
You could do alert(emailvalue); before the if statement to see if you get undefined or some value. If it's undefined, you probably have a scope issue.
From the above code it also seems that you assign those variables values, before anything is really entered or the form is submitted.

Categories

Resources