I am trying to make my input strings lower case using Dojo - javascript

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());

Related

How to check javascript nodelist if it's contents are either all empty or all have values?

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">

JavaScript validation using inputs as array

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;
}

Javascript try and catch

My code is not reporting any errors no matter what I do. This is for a indexed array and I was to get an error when I prompt user to enter the list number they want to delete. It should give me an error if its not in the index or not a integer.
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
try {
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else{
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
output.innerHTML = delMessage;
}
//Return false to prevent submission:
return false;
}catch(ex){
console.log(ex.message);
}
}
simple, add the below code to beginning of try block
if((input -parseInt(input ))!=0) throw new Error('not integer');
it should do the trick.
I changed your function, please see if it is what you want:
var tasks = [1,2,3,4,5,6,7,8,9,10];
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else if (delTask == 0){
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
document.getElementById('output').innerHTML = delMessage;
} else {
throw "The value is not number or not index of array! Try again!";
}
//Return false to prevent submission:
return false;
}
try {
deleteTask();
} catch (e) {
console.log(e);
}

Ensuring that an entered name doesn’t end with a space

I am trying to get it so that if I type in a name that ends with a space, the textfield will go red. Most of the code works its just one method does not seem to be working.
The issue must be somewhere in the last index part?
var NamePass = true;
function ValidateName() {
var BlankPass = true;
var GreaterThan6Pass = true;
var FirstBlankPass = true;
var BlankMiddleName = true;
if (document.getElementById('Name').value == "") {
BlankPass = false;
}
var Size = document.getElementById('Name').value.length;
console.log("Size = " + Size);
if (Size < 7) {
GreaterThan6Pass = false;
}
if (document.getElementById('Name').value.substring(0, 1) == " ") {
FirstBlankPass = false;
}
var LastIndex = document.getElementById('Name').value.lastIndexOf();
if (document.getElementById('Name').value.substring((LastIndex - 1), 1) == " ") {
FirstBlankPass = false;
}
string = document.getElementById('Name').value;
chars = string.split(' ');
if (chars.length > 1) {} else
BlankMiddleName = false;
if (BlankPass == false || GreaterThan6Pass == false || FirstBlankPass == false || BlankMiddleName == false) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
http://jsfiddle.net/UTtxA/10/
lastIndexOf gets the last index of a character, not the last index in a string. I think you meant to use length instead:
var lastIndex = document.getElementById('Name').value.length;
Another problem with that, though, is that substring takes a start and end index, not a start index and a substring length. You could use substr instead, but charAt is easier:
if (document.getElementById('Name').value.charAt(lastIndex - 1) == " ") {
FirstBlankPass = false;
}
Now, for some general code improvement. Instead of starting with all your variables at true and conditionally setting them to false, just set them to the condition:
var NamePass = true;
function ValidateName() {
var value = document.getElementById('Name').value;
var BlankPass = value == "";
var GreaterThan6Pass = value.length > 6;
var FirstBlankPass = value.charAt(0) == " ";
var LastBlankPass = value.charAt(value.length - 1) == " ";
var BlankMiddleName = value.split(" ").length <= 1;
if (BlankPass || GreaterThan6Pass || FirstBlankPass || LastBlankPass || BlankMiddleName) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
A couple more points of note:
It’s probably a good idea to use camelCase variable names instead of PascalCase ones, the latter usually being reserved for constructors
blah == false should really be written as !blah
An empty if followed by an else can also be replaced with if (!someCondition)
That function looks like it should return true or false, not set the global variable NamePass
Penultimately, you can sum this all up in one regular expression, but if you intend to provide more specific error messages to the user based on what’s actually wrong, then I wouldn’t do that.
function validateName() {
return /^(?=.{6})(\S+(\s|$)){2,}$/.test(document.getElementById('name').value);
}
And finally — please keep in mind that not everyone has a middle name, or even a name longer than 6 characters, as #poke points out.

Form Validation - How to use If and Else If

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...

Categories