3

I am currently working on a project that requires me to do a javascript form validation on a form that contains conditional input fields ( the visitor can choose whether to log in via a user number or email address ). Both input fields are separate and I need to do the following:

If visitor chooses to log in via option A ( user number ), the validation should only take into account the id of input field A ( the user number ) and not require validation for the other field ( email address ).

And vice versa, if visitor chooses option B.

The code I am currently using for validation:

function empty() {
var x;
x = document.getElementById("user_number").value;
if (x == "") {
    MsgBox('Your user number is required.', 'ERROR');
    return false;
}
var y;
y = document.getElementById("email").value;
if (y == "") {
    MsgBox('Your email address is required.', 'ERROR');
    return false;
}

}

And the form trigger event:

<form method="POST" id="accordion-top-form" action="" onsubmit="return empty();">

I need to expand the current script to check if either field A or field B has been filled in when submitting the form ( and then automatically disable validation for the other field ).

How do I do that?

6
  • MsgBox ? Sounds like VBA Commented Apr 15, 2017 at 5:35
  • kindly show full code .Where is the input field markup and choose option? Commented Apr 15, 2017 at 5:35
  • @prasad apart from the msgbox, all necessary code is present Commented Apr 15, 2017 at 5:35
  • Yes, the other code is in a file that defines a modal popup window - I don't think that's relevant, and it's kind of long anyways. What I need is how to expand those rules properly. Commented Apr 15, 2017 at 5:38
  • @James Others have already noted that MsgBox is not JavaScript, so this looks like some sort of hybrid code. In any case, you should investigate HTML5 form validation which has this sort of thing built in. Supported in all modern browsers, as well as IE>=10. Commented Apr 15, 2017 at 5:46

5 Answers 5

1

You could use the following:

var forms = {
  user: 0,
  email: 1
};

function whichForm() {
  var userForm = document.getElementById("user_number").value;
  var emailForm = document.getElementById("email").value;

  if (userForm && emailForm) {
    //user wrote in both forms, something is wrong
  } else if (!userForm && !emailForm) {
    //user didn't fill in any form
  } else {
    return userForm ? forms.user : forms.email;
  }
}

function empty(form) {
  if (form === forms.user) {
    // check if the user number form is empty
    var userForm = document.getElementById("user_number").value;
    if(userForm.trim() === "") {
      // possibly do more validation
      // return true or false based on whether you want to submit
    }
  } else if (form === forms.email) {
    // check if the email form is empty
    var emailForm = document.getElementById("email").value;
    if(emailForm.trim() === "") {
       // possibly do more validation
      // return true or false based on whether you want to submit
    }
  } else {
    // something is wrong, invalid parameter,
    // handle here
    return false
  }
}

function validate() {
  return empty(whichForm());
}

And change your form so that it calls return validate() inline or just validate as a submit handler.

Sign up to request clarification or add additional context in comments.

2 Comments

There are indeed a lot of points of failure, but all of them are either points of failure implicit in the form model of user input (What if fields are empty? What if user is only supposed to input data in one form but inputs in both?) which must be handled in some way, or points of failure in JavaScript's design (no way to create actual enumeration types with restricted values) which are better caught early in the development cycle through unit testing. Reducing the level of abstraction in order to make these failures "implicit" is likely to lead to trouble when you didn't predict some case.
My empty() function does not return because it is just an example. It is supposed to return a boolean, as indicated by the fact that my validate() function returns, which would have no point to it if empty didn't return anything, but since what to do on empty cases is app-specific I left it empty so the user who asked could fill it according to their needs. I'll edit to make this clearer.
1

Sounds like this would be enough?

I would personally not call the function empty since you want to return true to allow submission

function empty() {
  var x = document.getElementById("user_number").value,
      y = document.getElementById("email").value;
  x = x?x.trim()|| ""; // handle null and all blanks
  y = y?y.trim()|| "";

  if (x === "" && y === "") {
    alert("Please enter user number or email")
    return false;
  }
  // optional
  if (x && y) { // both entered
    alert("Please enter EITHER user number or email")
    return false;
  }

  if (x) return isValidUser(x); // each of these functions needs to return boolean
  if (y) return isValidEmail(y);

  // likely not going to happen
  return false;
}

Comments

0

You can test if both are empty

function empty() {
  var a = document.getElementById("user_number").value,
      b = document.getElementById("email").value;
  if ("" == a && "" == b) return MsgBox("Your user number or mibile is required.", "ERROR"), !1
};

1 Comment

This will allow a string of blanks in either
0

Code do it in this way:

function empty() {
  var x = document.getElementById("user_number").value,
    y = document.getElementById("email").value;
  if (!x && !y) {
    alert('You should choose email address or number');
    return false;
  }
  return true;
}

5 Comments

This will allow blank user/email
@mplungjan @ James need one of them email or number. isn't it ?
I can type in a space and it submits
@mplungjan Yup, you can use String.trim function to remove spaces. but there is a lot of missed validations not only this, i didn't validate email or user_number.
I was referring to your use of falsy/truthy instead of actual testing the content
0

Proposed solution: Check which of the two input fields is filled up:

var inputA = document.getElementById('A').value;
var inputB = document.getElementById('B').value;

if ((inputA !== "") || (inputA !== NaN) || (inputA !== undefined)) {
  //execute code for the user number
}
else if ((inputB !== "") || (inputB !== NaN) || (inputB !== undefined)) {
  //execute code for the email
}
else {
  //display an error saying none of the two fields were used
}





Recommendation: Most websites would only use 1 input because it looks a lot cleaner. And the place holder text can specify to the user what input options he should put in:

<input type="text" id="input1" placeholder="user number or email">

Proposed Solution: Check if the user input has a @ symbole:

var input1 = document.getElementById("input1").value;
var emailInput = input1.includes('@');//returns a boolean with a value of true
                                     //if '@' was found in the string input1
if (emailInput) {
  //execute the code for the email input
} else {
  //execute the code for the userID input
} 

Explanation:

I assumed that you wanted to use the same input field inside your <form ...> tag regardless if the user is using an email or an id number to log in. From that, what I saw as most logical is to just find something that is unique to one of those inputs, and base the logic of your code on whether that unique element existed in the input provided.

AKA since emails always have the @ symbol, verifying if this exists in the provided string or not should be enough to verify if the user used an email or id number to attempt to login.

Let me know if that helped :).

1 Comment

thanks for letting me know @mplungjan I believe it's been fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.