Hi I am trying to validate my inputs using JavaScript, I have the inputs in an array and I am trying to use them to extract information like .value and set values such as .className. This is not working as I would like it to. What I want the code to do is if I define input[1] = document.forms["register"]["username"]; then use input[1].value it interprets this as if I have written document.forms["register"]["username"].value
Here is my original code:
function validateForm() {
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}
Here is my updated code, I am unsure of whether this is good practice:
function validateForm() {
var error = false;
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
console.log(inputs.length);
for (i = 0; i < (inputs.length); i++) {
if (inputs[i].value == null || inputs[i].value == "") {
error = true;
inputs[i].className += " invalid";
if (inputs[i] == (inputs.length - 1)) {
alert("Highlighted fields must be filled out");
return false;
}
}
}
if (error == false) {
return true;
}
alert("Highlighted fields must be filled out");
return false;
}
The class invalid adds a red border to the field.
Thanks.
i changed your function a bit to read input elements as in the plnkr link below
https://plnkr.co/edit/zHhM6lmz3XA2u4CYr9h0?p=preview
function validate() {
var inputs = [];
var elements = document.forms["register"].elements;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.type === "text" || element.type === "email" || element.type === "password") {
inputs.push(element)
}
}
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}
I have handled three input types
text
email
password
You can add more later if needed
Edit: Possible cause of error can be DOM element not available inside the form (please share HTML if possible). First loop will read all available DOM element from the form.
function validateForm() {
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}
Related
I'm fairly new to javascript and looking at checking some fields with dynamic ID's at the end of the ID to see if they've either had values entered in all of them or none of them at all. The user shouldn't be allowed to only enter values in some of them and leave others blank.
I've wrote the below, which works, but I feel there must be a better way of doing this?:
var x = document.querySelectorAll('[id^="entryField"]');
for (var i = 0; i < x.length; ++i) {
if (x[i].value == "") {
for (var i = 0; i < x.length; ++i) {
if (x[i].value != "") {
alert("Please enter a value");
}
}
}
}
One loop should work with a counter for empty (or filled) fields. If the counter is not zero and does not have the length of the object, then some fields have a value.
var x = document.querySelectorAll('[id^="entryField"]'),
empty = 0;
for (var i = 0; i < x.length; ++i) {
if (x[i].value == "") {
++empty;
}
}
if (empty !== 0 && empty !== x.length) {
alert("Please enter a value");
}
This will be a simpler version:
var x = document.querySelectorAll('[id^="entryField"]');
const inputs = Array.from(x);
const allInput = inputs.every(input => {
return (input.value != "");
});
const allEmpty = inputs.every(input => {
return (input.value == "");
});
if (allInput || allEmpty) {
alert('xxxxxx');
}
ES5 implementation:
var x = document.querySelectorAll('[id^="entryField"]');
var inputs = Array.from(x);
var allInput = inputs.every(function(input) {
return (input.value != "");
});
var allEmpty = inputs.every(function(input) {
return (input.value == "");
});
if (allInput || allEmpty) {
alert('xxxxxx');
}
EDIT: Support allInput or allEmpty. Overlooked at the beginning.
You can check with two every calls, below will be true if all elements are filled or none of the elements are filled - every other case will be false:
var x = document.querySelectorAll('[id^="entryField"]');
var allowed = function allOrNone(elements) {
return Array.prototype.every.call(x, function(v) {
return v.value && v.value != "";
}) || Array.prototype.every.call(x, function(v) {
return !v.value || v.value == "";
});
}
console.log(allowed(x));
<input id="entryFieldFoo">
<input id="entryFieldBar">
I want to do form.submit() but only if all form items with the required attribute are full.
I was thinking on simpy iterating through the form children in search for the attribute, but I'm not sure how to do it since there might be nested elements and such. And probably there is an easier way to do it.
this.form_is_full = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].getAttribute("required") && form.elements[i].value=="")
{
// If has attribute required and is blank return false
}
}
return true;
}
How can I do this?
function Validate()
{
// create array containing textbox elements
//for example:
var inputs = [document.getElementById('fname'),
document.getElementById('lname'), document.getElementById('email'),
document.getElementById('messagetxt')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
Try this:
$('#YourFormId').submit(function(e) {
if ($.trim($("#YourFormId input").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});
This is what I did:
this.validate_form = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].value == "" && form.elements[i].getAttribute("name") && form.elements[i].hasAttribute("required"))
{
return false;
}
}
return true;
}
I trying to do some validation on a form with radio buttons in it. I can get the text elements to work fine but the radio buttons don't seem to like me.
function validateAll(theForm)
{
var err=0;
var fields;
for (var i=0; i<theForm.elements.length; i++)
{
fields =theForm.elements[i];
if(fields.type == "text" || fields.type == "textarea")
{
if(fields.value == "" || fields.value == null){
err++;
validateText(fields.id);
}
}
else if(fields.type == "radio"){
validateRadio(fields)
}
}
if(err > 0){return;}else{document.myform.submit();}
}
function validateText(id)
{
var x=document.forms["myForm"][id].value;
if (x==null || x=="")
{
var text = id+"Text";
document.getElementById(text).style.visibility ="visible";
return;
}else {
var text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return;
}
}
function validateRadio(radios)
{
var id = radios.id;
var text;
for (i = -1; i < radios.length; ++i)
{
if (radios[i].checked) {
text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return true
}}
text = id+"Text";
alert(text);
document.getElementById(text).style.visibility ="visible";
return false;
}
I am just calling it with a input button. Any ideas on why its not working? It turns the text on find but dose not turn it off.
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...
I have this security question answer input field validate function where I want to make sure the string are converted to lowercase just in case a user enter a answer in caps in the first field and in small case in the second field:
validate : function(){
//check if both input fields are not blank
//if not blank, check to see if they match and send back status message
var _inputs = dojo.query("#" + this.id + " input");
var _y = ""
var _matchingValues = [];
_this = this;
for(var i = 0, len = _inputs.length; i < len; i++) {
_matchingValues.push(_inputs[i].value);
}
dojo.forEach(_matchingValues, function(arr) {
if (arr == "") {
_this.status = "incomplete";
//_this.status = "invalid";
return _this.status;
}
else if (arr != _y) {
_y = arr;
_this.status = "nomatch";
return _this.status;
}
else if (arr.length < 3){
_this.status = "short";
return _this.status;
}
else {
_this.status = "valid";
return _this.status;
}
});
},
How can this be accomplished
_matchingValues.push(_inputs[i].value);
You can change this so it only pushes the lowercase values before you perform your comparison.
_matchingValues.push(_inputs[i].value.toLowerCase());