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>
Related
I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>
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/
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);
}
}
I can't figure out why this is not working as i did everything correct.
This is a simple create a account form. I put validation code for some of the field like name, email and password. There are many other fields. but first i m trying this.
The like is here:
jsfiddle
and the code of HTML:
First Name
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname />
<input type="text" name="remail" id="remail" />
New Pasword
<input type="password" name="rpass" id="rpass" />
<input name="regis" type="submit" class="color2" id="id" value="Submit" />
The javascript code here:
function validateRegis() {
//regex for fname and lname
var fname = $("#fname").val();
var lname = $("#lname").val();
var patt_n = /[a-z]{2,20}/i;
//checking fname and lname for regex matching
var ftest = patt_n.test(fname);
var ltest = patt_n.test(lname);
var remail = $("#remail").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9\_\.\-]+[a-zA-Z0-9\_\-]+#[a-zA-Z0-9]+[a-zA-Z0-9\.\-]+[a-zA-Z0-9]+\.[a-z]{2,4}$/;
var test = filter.test(remail);
var rpass = $("#rpass").val();
var patt = /[a-z0-9~!##$%^&*()_\ ]/i;
var test2 = patt.test(rpass);
if (fname === "" || ftest === false) {
alert("Please provide first name!");
$("#fname").focus();
return false;
} else if (lname === "" || ltest === false) {
alert("Please provide Last name!");
$("#lname").focus();
return false;
} else if (remail === "" || test === false) {
//
alert("Please provide email in correct format!");
$("#remail").focus();
return false;
} else if (rpass === "" || rpass.length < 8 || test2 === false) {
alert("Please provide password!");
$("#rpass").focus();
return false;
} else if ((fname !== "") & (lname !== "") & (remail !== "") & (test === true) & (rpass >= 8) & test2 === true) {
return true;
}
}
It needs jquery to run the code.
The problem is the validateRegis function is not available in the global scope.
In the fiddle UI left side panel, 2nd select box select No Wrap in body, it works fine.
Demo: Fiddle
When you select onLoad there, all the scripts under the script frame is wrapped under a anonymous function, so your validateRegis method becomes a local member of that anonymous function. Thus that function will not be available when the function submit is called causing an Uncaught ReferenceError: validateRegis is not defined error being thrown.
First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.