Validate a form with multiple elements? - javascript

I have a form that has multiple elements/types
inputs for name, email, address, etc.
radio button for shipping speed.
select tags for "state" & "credit card type".
I want to disable the submit button until the:
1.inputs are filled out.
the select tags have an option selected
the radio is checked.
I've selected the elements (see below);
const btn = document.querySelector('#olegnax-osc-place-order-button');
let inputs = document.querySelectorAll('#olegnax-osc-billing-address-list .required-entry, input#authorizenet_cc_number');
let selectTags = document.querySelectorAll('#olegnax-osc-billing-address-list select, #payment_form_authorizenet select');
let radio = document.querySelector('#s_method_owebiashipping1_id_06');
My question is, being the form consists of 3 different types (input, select, radio), can I just create one array with all of these elements and loop though to make sure the value for each is not blank?
For example, say I store all the different elements in an array called "requiredFields" would this work?:
for (var i = 0; i < requiredFeilds.length; i++) {
if (requiredFeilds[i].value === '') {
btn.disabled = true;
}else {
btn.disabled = false;
}
}

There's a lot more to form validation than meets the eye, but that being said you have a major flaw in your logic. Namely, as you loop over all the fields, you could be changing btn.disabled back and forth depending on the value of the form field (or lack of a value).
Instead, begin with the button disabled, and then instead of looping, use Array.prototype.some (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to check if any field is missing a value, something such as:
btn.disabled = requiredFields.some(field => field === '');
There's lots else to address with regards to your approach but this corrects your current logic error and is much more concise.

You can loop through everything but the radio buttons easily. For the radio buttons, you want to check if any of the buttons in a radio group are checked, so it is a little more complicated. It might be easier to just designate a radio button as default, with the checked attribute:
document.querySelector("input[type=submit]").disabled = true;
const inputs = Array.prototype.slice.call(document.forms["form1"].querySelectorAll("input[type=text], select"));
document.forms["form1"].addEventListener("input", () => {
let complete = true;
inputs.forEach((field) => {
if(field.value.trim() === "") {
complete = false;
}
});
document.querySelector("input[type=submit]").disabled = !complete;
});
form{
display:flex;
flex-flow:column;
align-items:flex-start;
}
<form name="form1" id="form1">
<input type="text" name="bar" />
<input type="text" name="foo" />
<select name="biz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<select name="baz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<label>
A <input type="radio" name="buzz" value="a" checked />
</label>
<label>
B <input type="radio" name="buzz" value="b" />
</label>
<input type="submit" value="Submit" />
</form>

Yes, just combine your selectors and use a comma, and check tagName:
const requiredFields = document.querySelectorAll( "
#olegnax-osc-place-order-button,
#olegnax-osc-billing-address-list .required-entry,
input#authorizenet_cc_number,
#olegnax-osc-billing-address-list select,
#payment_form_authorizenet select,
#s_method_owebiashipping1_id_06
" );
for( let input of requiredFields ) {
if( input.tagName == "INPUT" ) {
}
else if( input.tagName == "SELECT" ) {
}
else if( input.tagName == "TEXTAREA" ) {
}
}
You should also use the required attribute too:
<input type="text" required />
<select required></select>
<textarea required></textarea>

Related

Listen for blank inputs and add a "disabled" attribute to a button until an input is noticed

I have a user input field that, if blank, I would like the submit button to be disabled until a key press in the input box is noticed. But, if they blank out the input box, then the button is disabled again.
So, I'd like to add the "disabled" attribute to this input button:
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
The input is from this HTML here:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
Note: I have onkeypress and oninput validation to prevent non-number inputs and allow only 2 decimal places.
I assume my JS would look like this to add the disabled attribute:
document.getElementById("mapOneSubmit").setAttribute("disabled");
My problem is, I can't find what event listener listens for "blank" inputs? Can you help me with that?
Thanks kindly!
Check this one as well.
function checkvalid(el)
{
//e.g i am preventing user here to input only upto 5 characters
//you can put your own validation logic here
if(el.value.length===0 || el.value.length>5)
document.getElementById("mapOneSubmit").setAttribute("disabled","disabled");
else
document.getElementById("mapOneSubmit").removeAttribute('disabled');
}
<input type='text' id ='inp' onkeyup='checkvalid(this)'>
<button id='mapOneSubmit' disabled>
Submit
</button>
Yet using the input event:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this);updateSubmit(this.value)">
Then in js
function updateSubmit(val) {
if (val.trim() == '') {
document.getElementById('mapOneSubmit').disabled = true;
}
else {
document.getElementById('mapOneSubmit').disabled = false;
}
}
You can find the below code to find the blank inputs
function isNumberKey(event) {
console.log(event.which)
}
var value;
function validate(target) {
console.log(target);
}
<form>
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
</form>
You can you set the enable/disable inside validate function.
function validate(elem) {
//validation here
//code to disable/enable the button
document.getElementById("mapOneSubmit").disabled = elem.value.length === 0;
}
Set the button disable on load by adding disabled property
<input type="submit" id="mapOneSubmit" value="Submit" disabled>
On your validate function just check if value of input field is blank then enable/disable the button
function validate(input){
input.disabled = input.value === "" ;
}
My problem is, I can't find what event listener listens for "blank" inputs?
You can disable the submit button at render, after that you can use the input event to determine whether the input value is empty or not. From there, you can set state of the submit button.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('mapOneUserInput');
textInput.addEventListener('input', handleTextInput, false);
textInput.addEventListener('keydown', validateInput, false);
});
function handleTextInput(event) {
const { value } = event.target;
if (value) {
enableSubmitButton(true);
} else {
enableSubmitButton(false);
}
}
// Refer to https://stackoverflow.com/a/46203928/7583537
function validateInput(event) {
const regex = /^\d*(\.\d{0,2})?$/g;
const prevVal = event.target.value;
const input = this;
setTimeout(function() {
var nextVal = event.target.value;
if (!regex.test(nextVal)) {
input.value = prevVal;
}
}, 0);
}
function enableSubmitButton(isEnable) {
const button = document.getElementById('mapOneSubmit');
if (isEnable) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
}
<input type="number" value="" id="mapOneUserInput">
<!-- Note that the input blank at render so we disable submit button -->
<input type="submit" id="mapOneSubmit" value="Submit" disabled>

How to dynamically keep track of user inputs in JavaScript?

Does anyone have any idea to dynamically keep track of user inputs in a form? I learned how to disable a button and if users want to enable it, they would just have to fill in the input fields. While this works, if a user decides to backspace and go back to a clear field, the button is still enabled. I wanted to get some insight or ideas to keep track of user inputs dynamically.
I'm a bit new to JS so I just wanted some ideas. Is it possible to use for loops/forEach methods to iterate through the input fields? Or what approach do you recommend on taking?
HTML:
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" id="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
JavaScript:
document.getElementById("input").addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
if (inputs != "") {
document.getElementById("submitButton").removeAttribute("disabled");
} else if ((inputs = "")) {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
Here is the solution of your problem.
document.addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
var emptyFillExists = false;
for (let index = 0; index < inputs.length; index++) {
if (inputs[index].value.length === 0) {
emptyFillExists = true;
break;
}
}
if (!emptyFillExists) {
document.getElementById("submitButton").removeAttribute("disabled");
} else {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
There are a few things wrong with your codes:
You assume inputs as strings. It isn't. It's an array.
You track keyup event for only 1 input. You should track keyup event for all inputs instead.
Here's what I'd suggest you do:
Add event listener keyup for the form.
Interate through each input and check.
function areInputsValid() {
// Iterate through every input and check its value
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++)
if (inputs[i].value == '')
return false;
return true;
}
// Get the form element
var form = document.getElementsByTagName('form')[0];
// Add event listener
form.addEventListener('keyup', function() {
// Are the inputs valid?
if (areInputsValid())
document.getElementById("submitButton").removeAttribute("disabled");
else
document.getElementById("submitButton").setAttribute("disabled", null);
})
EDIT: as charlietfl pointed out, there are bugs in my previous answer.

How to combine on each element while response code from the php script and radio button is checked javascript

I try to achieve validation on multiple input elements.
Here is my HTML
<input class="date_of_birth" name="date[]" type="text" />
<span class="stepbirthVal"></span>
<input class="livingkid" type="radio" name="livingkid[]" value="1">Yes
<input class="livingkid" type="radio" name="livingkid[]" value="0">No
<input class="date_of_birth" name="date[]" type="text" />
<span class="stepbirthVal"></span>
<input class="livingkid" type="radio" name="livingkid[]" value="1">Yes
<input class="livingkid" type="radio" name="livingkid[]" value="0">No
Next
At the moment my code only check for the input field, but i want to combine it with radio button. Like when input is filled in it does not have response code 0 and radio button is checked, it has to look always both conditions if one of the is not correct remain Next button disabled.
This is my JS code
var livingkid = [];
$('.livingkid:checked').each(function(){
livingkid.push($(this).val());
});
//GET JSON from Validation.php and extract the nodes
var response = xmlhttp.responseText;
var parseJson = JSON.parse(response);
var resultCode = parseJson.code;
var resultMessage = parseJson.message;
//Remove disabled class from the next step button
var element = document.getElementById('stepbirth');
element.classList.toggle("disabled", parseJson.some(function (resp) {
return !resp.code;
}));
//Show Validation Message
var items = document.querySelectorAll(".stepbirthVal");
parseJson.forEach(function (response, i) {
return items[i].innerHTML = response.message;
});
How can i validate here with this classList.toggle each radio button is checked and response code = 1? else Next button remain disabled.
I hope you guys understand my question.
Thanks in advance.

Validating a form when either a "select" OR "input" is required

I have a page containing multiple forms, all different, and when one is submitted I use the function below to gather all the inputs from that form with the class "required" and check for empty values:
function validateForm(form) {
var inputs = form.getElementsByTagName('input');
var selects = form.getElementsByTagName('select');
var errors = 0;
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].classList.contains('required')) {
if(inputs[i].value === "") {
inputs[i].classList.add("warning");
errors++;
} else {
inputs[i].classList.remove("warning");
}
}
}
if(errors) {
return false;
} else {
return true;
}
}
If it finds an empty value, it adds the class "warning" which just gives the input a red border, then returns false so the form doesn't get submitted.
Here's where I'm running into trouble: Some forms contain a <select> and a text input, ONE of which must be filled in, but not both, as well as various other text inputs. I'm trying to figure out how to modify the above function to handle this.
Let's say the form is for adding a new product. The select is dynamically populated with existing product "categories" and the text input is for if the user wants to create a new category. Here's a simplified version of the form:
<form method = "post" onsubmit = "return validateForm(this)">
<div class = "form-group">
<label>Product Name</label>
<input class = "form-control required" type = "text" name = "product" />
</div>
<div class = "form-group">
<select class = "form-control required" id = "category" name = "category[]">
<option value = "">Select Existing Category</option>
<option value = "Shirts">Shirts</option>
<option value = "Shoes">Shoes</option>
<option value = "Pants">Pants</option>
</select>
</div>
<div class = "form-group">
<label>Create New Category</label>
<input class = "form-control required" type = "text" name = "category[]" />
</div>
<div class = "form-group">
<input class = "btn btn-primary" type = "submit" value = "Submit" />
</div>
</form>
Since I'm using a for loop to go through the inputs - the select and the input are not going to have the same index, so I can't do something like this:
if((selects[i].value === "" && inputs[i].value === "") || (selects[i].value !== "" && inputs[i].value !== "")) {
// add the warning class to both
}
I feel the answer lies somewhere in using the name attribute, i.e. compare selects.name and inputs.name, but how do I get around the differing index in the loop? And also, it should only make this comparison when the select is encountered anyway. It doesn't necessarily exist, depending on the form.
Basically, I need to modify my function to do this:
I. Gather all inputs and selects (if any - some forms will not) from a submitted form
II. Make sure none of the inputs with the "required" class are blank (unless there's a corresponding select, in which case see III below)
III. If there's a select, find the text input with the same "name" (not a requirement to have the same name, but I assume this is the right way to do it). One of them, but not both, must have a value. If both are blank, or both have a value, they should get the "warning" class;
Any help anyone can offer will be greatly appreciated!
Here's a function that do exactly what you want and can handle any form you want, as long as they have the same HTML structure.
Notes:
I recommend avoiding inline event listeners as much as you can, in
the snippet below I used addEventListener method to attach submit
event to all the forms in the document, you can change this to just
some specific forms if you want.
Instead of only adding a border to the required elements, I suggest
you also add some text to tell what the problem is.
// getting all forms in the page you can also get specific forms based on their class-name
var forms = document.getElementsByTagName('form'),
l = forms.length,
i = 0;
// adding submit submit event listener to the referenced forms
for(; i < l; i++) {
forms[i].addEventListener('submit', validateForm);
}
function validateForm(e) {
var els = this.querySelectorAll('input.required'),
len = els.length,
err = false,
c = 0,
inpName = '';
// checking if the form has a select, if so, allow only the select or the input to be filled
var isSelect = this.getElementsByTagName('select');
if(isSelect[0] !== undefined && isSelect[0] !== null) {
var inp = isSelect[0].parentNode.nextElementSibling.querySelector('input.required');
inpName = inp.name;
if((isSelect[0].value == '' && inp.value.trim().length === 0) || (isSelect[0].value != '' && inp.value.trim().length > 0)) {
err = true;
isSelect[0].classList.add("warning");
inp.classList.add("warning");
} else {
isSelect[0].classList.remove("warning");
inp.classList.remove("warning");
}
}
// iterate through the rest of the inputs and check for empty one, thus trimming them before checking
for(; c < len; c++) {
if(els[c].name !== inpName) {
if(els[c].value.trim() == '') {
err = true;
els[c].classList.add("warning");
} else {
els[c].classList.remove("warning");
}
}
}
// based on the error variable, either submit the form or cancel submission
(!err) ? this.submit():e.preventDefault();
}
.warning {
border: 2px solid red;
}
<form method="post">
<div class="form-group">
<label>Product Name</label>
<input class="form-control required" type="text" name="product" />
</div>
<div class="form-group">
<select class="form-control required" id="category" name="category[]">
<option value="">Select Existing Category</option>
<option value="Shirts">Shirts</option>
<option value="Shoes">Shoes</option>
<option value="Pants">Pants</option>
</select>
</div>
<div class="form-group">
<label>Create New Category</label>
<input class="form-control required" type="text" name="category[]" />
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
Hope I pushed you further.
You may get a message saying: "The custom error module does not
recognize this error." when you successfully submit the form from the
snippet above, that due to StackOverflow's restrictions as they
don't allow/server side code (StackOverflow doesn't let the form to
be submitted).

How do I prevent invalid characters from being entered into a form?

For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/

Categories

Resources