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?
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.
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;
}
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
};
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;
}
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 :).
Related
I have a form with empty field validation. But when i'm trying to submit the form with some input fields filled, it is executing both conditions given under if and else statement.
JS
let inputTags = document.querySelectorAll( 'input' )
for ( let input of inputTags )
{
if ( input.value === "" && !input.classList.contains( 'hidden' ) )
{
promptMessages( 'All fields are required.' )
input.focus()
break;
}
else
{
console.log( input.value )
}
}
How do I ensure that else condition is executed only when all fields are filled and not when some are.
OR
Is there a better way to validate the form by using just JS?
At the moment you are checking each input separately and go to the else clause, if the if clause isn't fulfilled. If you want to only execute the else clause, when all fields are filled, then you could for example use a flag outside the for-loop.
const inputTags = document.querySelectorAll('input');
let allFilled = true;
for (const input of inputTags){
if (input.value === "" && !input.classList.contains('hidden')){
promptMessages('All fields are required.');
input.focus();
// Set the flag to false, since at least one input isn't filled
allFilled = false;
break;
}
}
// Check if flag is true
if (allFilled) {
// Execute the code, which was previously in the else clause
console.log( input.value )
}
There are other ways to do it, but this is one example.
I have the following code which is being used as validation on input fields. However, I'm getting stuck as it's checking input filetype fields as well, which I don't want it to do. Is there a way of getting it to ignore an file input field?
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
//I only want the following condition statement to run if the current element is not a file field.
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
One option is to use querySelectorAll instead, and use :not([type="file"]):
y = x[currentTab].querySelectorAll('input:not([type="file"])');
You can also consider making the fields required to help improve UI, in addition to the Javascript.
To refactor a bit, consider using more meaningful variable names, and using classList.add so as to avoid adding duplicate class attributes to elements:
function validateForm() {
const thisTab = document.getElementsByClassName("tab")[currentTab];
const inputs = thisTab.querySelectorAll('input:not([type="file"])');
let valid = true;
for (const input of inputs) {
if (input.value === '') {
input.classList.add('invalid');
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
thisTab.classList.add('finish');
}
return valid; // return the valid status
}
how will i write a javascript code that will prompt a user to enter their name,check the input and return either good or bad I want the code to return that’s a bad name if the user inputs Shane and I want the code to return that’s a good name if the user inputs any other name.
var x = prompt("enter a name")
if(x == 'Shane') { alert('bad name'); } else { alert('good name'); }
as a function
function isNameGood(){
var x = prompt("enter a name")
if(x == 'Shane') { return 'bad name'; } else { return 'good name'; }
}
use as this:
var good_or_bad = isNameGood();
You can also achieve this by using Ternary operator.
var x = prompt("enter a name");
x == 'Shane'? alert('bad name') : alert('good name');
It means that if condition is true then the one after ? will be executed and if false, one after : will be executed.
Here condition is x=='Shane'.
You can simply use the var name = prompt('What is your name');
If you need advanced functionality you'll have to bring up your own interface and collect the input via the var name = document.getElementById('nameInp').value; function or with jQuery var name = $('#nameInp').val();. Now you construct the function and the if statement for how you will check. You've got the value of the persons name at the least.
Quick References:
https://www.w3schools.com/js/js_popup.asp
I'm looking for a way to use JavaScript to require a specific ratio of fields in a form to be complete. So if I have six fields and the user has to complete any 2/6 to submit. If not then they receive an error. (The form will actually have a few different groups like this in it, so I have to be able to identify specific fields for the ratio.)
After some more research I've found something close, and realize I can count the number of a class. How would I change this to say if number of checked boxes is greater than or equal to 2, return true?
document.getElementById("test").onclick = function() {
isCountCheck("Check something");
};
function isCountCheck(helperMsg) {
var i, len, inputs = document.form1.getElementsByClassName("checkbox");
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) return true;
}
alert(helperMsg);
return false;
}
UPDATE:
My final jQuery ended up like this.
function isCountCheck(){
if($("input[class=crit1]:checked").length >= 4)
return false;
alert("Check a box");
return true;
}
Using jQuery
var numberOfInputsCompleted = 0;
var allInputs = $(":input"); // returns all input fields on the document
var numberOfInputs = allInputs.length
allInputs.each(function () {
if($(this).val() != '') {
numberOfInputsCompleted = numberOfInputsCompleted + 1;
}
});
numberOfInputsCompleted would give fields completed and numberOfInputs would total number of input fields on the form. Hope this helps
The first thing that comes to my mind: create a function that counts filled fields and returns true if the number of filled fields is enough (false otherwise). Then add it to the form as an "onsubmit" function. When the submit button is clicked the function is executed and, depending on what the function returns (true or false), the form is submitted or not.
More info about javascript form validation: http://www.w3schools.com/js/js_form_validation.asp
I am trying to if the value of an input box is blank or not by doing the below:
var id = $(this).attr('id').substr(3);
var lengthname = $("#input_name_"+id).val().length;
var lengthrss = $("#input_rss_"+id).val().length;
if (lengthrss!=0 || lengthname!=0)
{
// do something
}
else
{
alert('Values cannot be blank');
}
For some reason it is not doing the OR however if the user enters both values as blanks then the alert comes up??
What you are looking for is an AND operation, not OR. The valid case is when both lengths are non-zero:
if (lengthrss!=0 && lengthname!=0)
{
// do something
}
Alternatively:
if (lengthrss==0 || lengthname==0)
{
alert('Values cannot be blank');
}
For reference: De Morgan's laws