JavaScript no response with validation - javascript

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.

Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2

The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.

Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.

I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.

replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Related

Checking if fields are empty in Javascript?

I am trying to check if specific fields are empty or not so I can Authenticate users using Firebase. However JavaScript seems to be skipping over multiple bits of code and constantly only showing the same message onscreen. Here is my code...
let user = document.getElementsByName('username');
let em2 = document.getElementsByName('mail2');
let rem = document.getElementsByName('repeatMail');
let pass2 = document.getElementsByName('password2');
let rpass = document.getElementsByName('repeatPassword');
if ((user === '') && (em2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((rem === '') && (pass2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if (rpass === '') {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((em2 !== rem) && (pass2 !== rpass)) {
alert('Please make sure all repeat fields match their parents. Thank you');
} else {
checkUsername()
}
It will constantly just skip to the last else if statement and no matter what will always give me the error I setup even if the fields do match in HTML. I am probably just overlooking something but I have been struggling with this for a while now. Does anyone know a solution? By the way this code is inside a function but that but I've given that a unique name and all it is, is a simple...
function regSecurity() {
}
Beside the neede value property of the input elements, you need to check for emptyness and then to check if both wanted inputs are the same.
function checkUsername() {
console.log('checkUsername');
return false;
}
function check() {
let user = document.getElementById('username').value,
em2 = document.getElementById('mail2').value,
rem = document.getElementById('repeatMail').value,
pass2 = document.getElementById('password2').value,
rpass = document.getElementById('repeatPassword').value;
if (!user || !em2 || !rem || !pass2 || !rpass) {
alert('Please make sure all fields are filled in correctly. Thank you');
return false;
}
if (em2 !== rem || pass2 !== rpass) {
alert('Please make sure all repeat fields match their parents. Thank you');
return false;
}
return checkUsername();
}
<form onsubmit="return check()">
<input type="text" id="username" placeholder="username">
<input type="text" id="mail2" placeholder="mail2">
<input type="text" id="repeatMail" placeholder="repeatMail">
<input type="text" id="password2" placeholder="password2">
<input type="text" id="repeatPassword" placeholder="repeatPassword">
<input type="submit">
</form>

How to return a light box error message from a function

I've created a basic form validation script that I want to return an error messages as a light box, rather than using an alert() message. I like the look of featherlight.js, but I can't figure out how to return it from a function? Any other suggestions would be greatly appropriated. Thanks in advance.
The featherlight.js repo
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
alert('Please enter your first name');
return false;
}
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>
I know this is a bit late, but I think I know what you're after. I've just done a similar thing myself, so I'll put it here incase it helps anyone.
I created a function so you can re-use it elsewhere along with an OK button to close the light box.
function customAlert(message = '') {
var alertBox = $(document.createElement('div'));
alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
$.featherlight(alertBox);
}
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
customAlert('Please enter your first name');
return false;
}
}
Basically, you cannot "return" it. What you can do is you can trigger a lightbox event when your conditions are match, like this:
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
$.featherlight($content, $configuration); // Lightbox for wrong validation
return false;
} else {
$.featherlight($content, $configuration); // Lightbox for successful validation
return true;
}
}
And of course, you will need to modify $content and $configuration variables as you want as explained here:
https://github.com/noelboss/featherlight/

How to make input required

What I want is that when both fields i.e. fname and lname are kept empty, the pop-up window should show both messages i.e. "First name must be filled out", "Last name must be filled out".
What modifications do I need to do?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
document.myForm.fname.focus();
return false;
}
var y = document.forms["myForm"]["lname"].value;
if (y == null || y == "") {
alert("Last name must be filled out");
document.myForm.lname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">First name:
<input type="text" name="fname">Last name:
<input type="text" name="lname">
<input type="submit" value="Submit">
</form>
</body>
Perhaps this will give you some ideas about how to proceed:
function validateForm() {
var errors = [],
fname = document.forms["myForm"]["fname"],
lname = document.forms["myForm"]["lname"];
if (lname.value == "") {
errors.unshift("Last name must be filled out");
lname.focus();
}
if (fname.value == "") {
errors.unshift("First name must be filled out");
fname.focus();
}
if (errors.length > 0) {
alert("Cannot submit\n" + errors.join("\n"));
return false;
}
}
Demo: http://jsfiddle.net/MKdg5/
The first thing you'll notice is that it is easier to read because blocks are indented. Also:
You currently use document.forms["myForm"]["fname"] and document.myForm.fname to access the same field. Pick one way and use it consistently, or
Create a variable that references the field, fname, and then use fname.value and fname.focus()
Don't bother testing for null because the .value property never will be.
Instead of immediately alerting an error and returning, add the error text to an array and then at the end test if the array is empty.
You can go with Hthml 5 required. It's so much simpler and neat.
<form>
First name: <input type="text" name="fname" required="required">
Last name: <input type="text" name="lname" required="required">
<input type="submit" value="Submit">
</form>
Demo
Note: The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. But it is not supported in Internet Explorer 9 and earlier versions, or in Safari.
Try to validate your field as:
if (!x || x.length == 0)
BAsed on your validateForm function, your code would never check the second field. When using the return statement, the function will stop executing, and return the specified value.
A solution is use nested if statements and check both fields in one conditional block
if (x==null || x=="")
{
if (y==null || y=="")
{
//codes for both are not validated
}
else
{
//codes for just x is not validated
}
}
else
if (y==null || y=="")
{
//codes for y is not validated
}
else
{
//codes for all validated
}
This way use of return statement in each block won't break your function execution

Wrapper Function not working properly (Javascript)

I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/

form still submitted after return false javascript

I'm having a little problem with a validation thing in javascript.
<form action="insert.php" id="form" name="form" method="post"
onSubmit="return validate()">
<pre>
Vul hier de/het E-mail adres(sen) in
<textarea name="email" rows="5" cols="50"></textarea><br>
Typ hier de E-mail
<textarea name="text" rows="5" cols="50"></textarea><br>
<input type="submit" name="Submit" value="Submit">
</pre>
</form>
As you can see here, I've got two textareas. In the upper one, you're supposed to enter one or multiple email addresses underneath eachother, and in the bottom textarea you're supposed to compose the email itself. Then, when you click on submit, it'll send the email to all those specified email addresses.
Now, I've made a validation for both textareas:
function explodeArray(emailID, delimiter) {
tempArray = new Array(1);
var Count = 0;
var tempString = new String(emailID);
while (tempString.indexOf(delimiter) > 0) {
tempArray[Count] = tempString.substr(0, tempString.indexOf(delimiter));
tempString = tempString.substr(
tempString.indexOf(delimiter) + 1,
tempString.length - tempString.indexOf(delimiter) + 1
);
Count = Count + 1
}
tempArray[Count] = tempString.replace("\r", "");
return tempArray;
}
function validate() {
var emailID = document.form.email;
var delimiter = "\n";
var emailArray = explodeArray(emailID.value, delimiter);
var textID = document.form.text;
var length = emailArray.length,
element = null;
for (var i = 0; i < length; i++) {
emailVar = emailArray[i];
if (emailVar == null) {
alert("Email-adres bestaat niet")
emailID.focus()
return false
}
if (emailVar == "") {
alert("Email-adres veld is leeg")
emailID.focus()
return false
}
if (checkEmail(emailVar) == false) {
emailVar.value = ""
alert("Ongeldig E-mail adres");
emailVar.focus()
return false
}
}
if ((textID.value == null) || (textID.value == "")) {
alert("E-mail textveld is leeg")
textID.focus()
return false
}
document.getElementById("form").submit();
return true
}
function checkEmail(hallo) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(hallo)) {
return true
}
return false
}
(I probably copied lots of irrelevant code as well, sorry for that, just copied the whole thing just in case...)
Now what does work is:
-it won't submit when both textareas are empty;
-it won't submit when the email addresses are valid but the bottom textarea is empty;
What doesn't work is:
-the form still submits when the email addresses are invalid, even when the bottom textarea is still empty.
I've been trying to figure out for hours what could possibly be wrong here, I googled and checked stackoverflow, but I really could not find anything. Could anybody tell me what I'm doing wrong here?
Thanks in advance.
You were using emailVar.focus(); which won't execute.
Here, fixed: Live Demo
if (checkEmail(emailVar) == false) {
alert("Ongeldig E-mail adres");
emailID.focus();
return false;
}

Categories

Resources