Simple JavaScript validation not working? - javascript

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm

Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.

You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

Related

html javascript form no longer working since adding new input field

I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">

Form Validation not responding correctly

I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.

Form validation using html and javascript

I'm trying to create a form validation using HTML and pure JavaScript as a part of my assignment. However, the age and password validation don't seem to work even with tinkering a lot with code. The age is supposed to be valid if it is between 18 to 60 and the password must be the same as well as according to regex.
Here's the extended code:
Edit: the uage code has been edited but still doesn't work as intended.
function checkPassword(str) {
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
}
function checkName(str) {
var ge = /^[a-zA-Z ]+$/;
return ge.test(str);
}
function mytq() {
var uname = document.forms.formvalidation.fullname;
var uemail = document.forms.formvalidation.email;
var uage = document.forms.formvalidation.age;
var upwd = document.forms.formvalidation.password;
var vpwd = document.forms.formvalidation.pwdrpt;
if (uname.value != "") {
if (!checkName(uname.value)) {
window.alert("Please enter a valid name");
uname.focus();
return false;
}
}
if (!(uage < 16 || uage > 60)) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}
if (uemail.value.indexOf("#", 0) < 0 && uemail.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid email");
uemail.focus();
return false;
}
if (upwd.value != "" && upwd.value == vpwd.value) {
if (!checkPassword(upwd.value)) {
window.alert("The password you entered is not valid");
upwd.focus();
return false;
}
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript">
</script>
</head>
<body>
<form name="formvalidation" method="POST" onsubmit="return mytq();" action="#">
<h1>Welcome to FTN.</h1>
<p>Fill this form before</p>
<hr>
<label for="name"><b>Full Name</b></label>
<input type="text" name="fullname" placeholder="Full Name" required>
<label for="email"><b>Email</b></label>
<input type="text" name="email" placeholder="Email" required>
<label for="age"><b>Age</b></label>
<input type="number" name="age" required>
<label for="password"><b>Password</b></label>
<input type="password" name="password" placeholder="Password" required>
<label for="password-repeat"><b>Re-type password</b></label>
<input type="password" name="pwdrpt" placeholder="Re-type Password" required>
<hr>
<p>By creating this account, you are agreeeing our terms and condition</p>
<button type="submit" class="registerbtn">Submit</button>
</form>
</body>
</html>
Your age comparison is flawed. If you wish to ensure that the age is greater than 16 and less than 60, you should simplify it to
if(uage < 16 || uage > 60) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

i need help making a status bar label

I need to make a labeled button that checks all the previous boxes I have above it and then reports back whether they are valid or not by putting the status on the screen after the button without popping up an alert, I am doing this in JavaScript so any help would be appreciated.
Here is what I have so far:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x){
x.style.background="yellow";
}
function validateForm(){
var Fid=document.getElementById("firstName").value;
if (Fid.length < 3) {
alert("first id is not valid");
return;
}
var Lid=document.getElementById("lastName").value;
if (Lid.length < 3) {
alert("Last id is not valid");
return;
}
var Age=document.getElementById("age").value;
if (Age.length == 0) {
alert("Age is not valid");
return;
}
} //End validateForm()
<script language="javascript">
function checkEmail() {
var email = document.getElementById("email");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert("Please provide a valid email address");
email.focus;
return false;
}
}
</script>
</script>
</head>
<body>
First id: <input type="text" id="firstName" onFocus="myFunction(this)"><br>
Last id: <input type="text" id="lastName" onFocus="myFunction(this)"><br>
Age: <input type="text" id="age" onFocus="myFunction(this)"><br>
E-mail address: <input type="text" id="email" onFocus="myFunction(this)"><br>
<label id="status">status</label><br>
<button id="CheckButton" onClick="return validateForm();">Check Form</button>
</body>
</html>
Instead of alerting, just set the innerHTML of your status label:
var Fid=document.getElementById("firstName").value;
if (Fid.length < 3) {
var status = document.getElementById('status');
status.innerHTML = status.innerHTML + '<br>First id is not valid';
//alert("first id is not valid");
return;
}
Based on your comment, modify your HTML like so:
First id: <input type="text" id="firstName" onFocus="myFunction(this)"><br>
Last id: <input type="text" id="lastName" onFocus="myFunction(this)"><br>
Age: <input type="text" id="age" onFocus="myFunction(this)"><br>
E-mail address: <input type="text" id="email" onFocus="myFunction(this)"><br>
<span id="status">status</span><br>
<div id='firstNameDiv' style='display: none'>First id is not valid</div>
<div id='lastNameDiv' style='display: none'>Last is id not valid</div>
<div id='ageDiv' style='display: none'>Age is not valid</div>
<div id='emailDiv' style='display: none'>Email is not valid</div>
<button id="CheckButton" onClick="return validateForm();">Check Form</button>
And your javascript like this:
var Fid=document.getElementById("firstName").value;
if (Fid.length < 3) {
document.getElementById('firstNameDiv').style.display = "";
}
else {
document.getElementById('firstNameDiv').style.display = 'none';
}

Categories

Resources