I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.
Related
i've applied validation to my form through jquery and in that form i've four checkboxes and the user must check one to submit form.
this is the code:
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox' && c[i].checked == true) {
return true;
} else {
error += alert ("You must select atleast one previous benefit provided");
return false
}
}
the problem is that this use return key and if i remove return key it will alert 4 times (same number of checkboxes) and if i let it be there then the if statement which check fields and give error don't work
if(error != "") {
$("#error").html("<strong>Some fields are invalid!</strong>") || error;
return false;
} else {
return true;
}
if i remove return in checkbox validation then everythings work fine but it give alerts four times and if dont remove it then without giving error it submit the form.
alert() doesn't return anything so your error logic doesn't make sense.
Create a collection of checked checkboxes and make sure it has length instead.
var hasChecked = $('#myForm :checkbox:checked').length;
if(!hasChecked){
return false
error = true;
}
I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}
The following script should validate only certain input fields depending on the selection a user makes in a drop-down box (var problem).
The trouble I'm having is when the if statement runs for problem == 4 (below) and the user has filled in the corresponding cityid field, the alert (Alert#3) for the next if statement (problem == 5) is triggered. I only want Alert#3 to trigger if the user has selected problem == 5 from the drop-down AND has not filled in the model field.
The same trouble happens respectively when if statement runs for problem == 5.
function ValidateSOR()
{
var user = document.SOR.User;
var problem= document.SOR.Problem;
var cityid = document.SOR.CityID;
var errors1 = document.SOR.ErrorCodes1;
var model = document.SOR.Model;
var errors2 = document.SOR.ErrorCodes2;
var software = document.SOR.SoftwareType;
if (user.value == "")
{
window.alert("Please enter your name.");
user.focus();
return false;
}
if (problem.selectedIndex < 1)
{
alert("Alert#1");
problem.focus();
return false;
}
if (problem.selectedIndex == 4)
{
cityid.focus();
}
else if (cityid.value == "")
{
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5)
{
model.focus();
}
else if (model.value == "")
{
alert("Alert#3");
model.focus();
return false;
}
if (problem.selectedIndex == 6)
{
software.focus();
}
else if (software.value == "")
{
alert("Alert#4");
software.focus();
return false;
}
return true;
}
You're not returning from the function when you discover that the problem is #4. Thus, because it is 4, then it's not 5, and so the "else" part of that branch is taken.
edit — OK, let's look at the code:
if (problem.selectedIndex == 4) {
cityid.focus();
}
else if (cityid.value == "") {
alert("Alert#2");
cityid.focus();
return false;
}
if (problem.selectedIndex == 5) {
model.focus();
}
else if (model.value == "") {
alert("Alert#3");
model.focus();
return false;
}
If the index is 4, what happens? This code runs:
cityid.focus();
Then what? The code proceeds to the next if statement:
if (problem.selectedIndex == 5) {
Now, if we just got through noticing that the index was 4, then what are the chances that it will be equal to 5? Zero! Thus, that comparison is guaranteed to be false, so we move to the else part. Apparently, your "model.value" is the empty string, so that if statement succeeds. You get the alert.
I think your problems would be solved by bringing the logic of the code more in line with the logic of your validation process:
if (problem.selectedIndex == 4 || cityid.value == "") {
cityid.focus();
return false;
}
That way, if the index is 4 or if the city ID value is empty, then you'll treat that as an error with the city ID and exit the function. It won't matter what comes after that, because the return leaves the function at that point.
You should restructure each IF like so:
if (problem.selectedIndex == 4 || cityid.value == "")
{
cityid.focus();
return false;
}
if (problem.selectedIndex == 5 || model.value == "")
//and so on
so it returns either way and does not hit the next if statement
I'm asking this because I am at a complete loss myself and need a fresh pair of eyes.
The following JavaScript function is successfully called on submission of the connected HTML form. The function starts and the first two if statements run (and halt the submission if they return false).
Then, the first test alert "before" appears and then the form submits, completely missing out the rest of the function. While testing I changed the final line to return false so that whatever happen the function should return false, but the form still submitted.
function validateForm(form)
{
// declare variables linked to the form
var _isbn = auto.isbn.value;
var _idisplay = auto.isbn.title;
var _iref = "1234567890X";
// call empty string function
if (EmptyString(_isbn,_idisplay)==false) return false;
// call check against reference function
if (AgainstRef(_isbn,_iref,_idisplay)==false) return false;
// call check length function
alert("before");///test alert
////// FORM SUBMITS HERE?!? /////////////
if (AutoLength(_isbn)==false) return false;
alert("after");///test alert
// if all conditions have been met allow the form to be submitted
return true;
}
Edit: this is what AutoLength looks like:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; {
else {
if (_isbn.length == 10) {
return true; {
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
There are errors in your implementation of AutoLength. Currently, it looks like this:
function AutoLength(_isbn) {
if (_isbn.length == 13) {
return true; { // <------ incorrect brace
else {
if (_isbn.length == 10) {
return true; { // <------ incorrect brace
else {
alert("You have not entered a valid ISBN10 or ISBN13. Please correct and try again.");
return false;
}
}
See how it doesn't close all of its blocks? That's because you've used the wrong brace in two places, and you've forgotten to close the function.
You could rewrite the function like this:
function AutoLength(_isbn) {
return _isbn.length === 13 || _isbn.length === 10;
}
If you're hell-bent on using alert, you can do that inside validateForm (although I would try to find a more user-friendly way to show the error message).
In the future, when you're trying to debug code, you can use try and catch to "catch" Errors as they happen, like this:
try {
if (false === AutoLength(_isbn)) {
return false;
}
} catch (e) {
alert('AutoLength threw an error: '+e.message);
}
If the execution of the function is terminated by a runtime error, the form submits. So check out the script console log for error messages.
I have variable deleteboxvalue
var deleteboxvalue = "111111111111111";
if(deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected."); return true;
}
I want to check if 0 is not exist in this I want to return false and alert as "You can't delete all Contact Number." but in both cases if 0 exist in variable in that case also its returning false and giving me alert as "You can't delete all Contact Number."
I want to check if 0 is not exist in this I want to return false
If that's the case then you've got your logic reversed. You are currently returning false if 0 is in the string (i.e. it is found at an index greater than or equal to 0). If you want to return false when 0 is not found in the string, you can do this:
if(deleteboxvalue.indexOf('0') == -1) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected.");
return true;
}
However, I may have completely misunderstood what you're trying to do...
Create a function in JavaScript such as:
function CheckContacts() {
var deleteboxvalue = "111111111111111";
if (deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
} else {
alert("All Zeros are not selected."); return true;
}
}
and
On body onload call that JavaScript method:
<body onload="CheckContacts()">