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

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.

Related

Finding the number of words without split() or heavy regex

Ive been struggling with this a bit and haven't found anything good on the website. I'm trying to find the number of words in a textarea without split() (cuz it counts whitespaces and miscounts words in some situations) this is what i've tried :
text.addEventListener('input', () => {
let wordCounter = 0;
let sentenceCounter = 0;
let charCounter = text.value.split('').length;
let flag = false;
let flag2 = false;
if(text.value === ' ' || text.value === ''){
wordCounter = 0;
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == '.' && flag == false){
sentenceCounter++;
flag = true;
}
if((/\w/).test(text.value[z])){
flag = false;
}
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == " " && flag2 == false){
wordCounter++;
flag2 = true;
}
if((/\w/.test(text.value[z]))){
flag2 = false;
}
}
sentences.innerHTML = `${sentenceCounter} : Sentences`
char.innerHTML = `${charCounter} : Characters`
words.innerHTML = `${wordCounter} : Words`
});
the problem here is that it counts words only if press space so that means "fa" is not counted as a word but "fa " is. Thanks in advance for your help!
You need to increase the counter when you find a letter, instead of when you find a space. You can also count words and sentences on the same loop. To finish a word, had to change from comparing to " " to \W.
let sentenceCounter = 0, sentenceFinished = false,
wordCounter = 0, wordFinished = true,
input = "Test text. Test.";
for (let z = 0; z < input.length; ++z) {
var letter = input[z];
if (!sentenceFinished && letter == ".") {
sentenceCounter++;
sentenceFinished = true;
}
if (sentenceFinished && /\w/.test(letter)) {
sentenceFinished = false;
}
if (!wordFinished && /\W/.test(letter)) {
wordFinished = true;
}
if (wordFinished && /\w/.test(letter)) {
wordCounter++;
wordFinished = false;
}
}
console.log(`Words: ${wordCounter}, Sentences: ${sentenceCounter}`);

Try and catch for check sum validation on input to check three parts of an input in Javascript

Bouncing my head off the wall here trying to figure out a better way to handle this. I have a large input value which has three checks to check the sum of certain parts of the string in order to validate it. I'm using three try/catch blocks in one function to run the check right now and it seems to be working except for the final validation check which always seems to return true. What I'm wondering is a) is this a good method to use, b) is there a cleaner way to do this with for loop and c) why my final check is not doing anything. Any help is appreciated. I have access to jQuery and Underscore.js if that helps but I have not worked much with underscore. I made a fiddle here:
Sample Fiddle
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
// run the checksum
var valid = false;
try {
var sum = (parseInt(number[0]) * 7) +
(parseInt(number[1]) * 3) +
(parseInt(number[2])) +
(parseInt(number[3]) * 7) +
(parseInt(number[4]) * 3) +
(parseInt(number[5])) +
(parseInt(number[6]) * 7) +
(parseInt(number[7]) * 3) +
(parseInt(number[8]));
alert(((sum % 10).toFixed(0)));
var checkDigit = ((sum % 10).toFixed(0));
if ((number[9]) === ("" + checkDigit)) {
alert('Our Checkdigit is valid', checkDigit);
valid = true;
}
} catch (e) {
alert('Fail for check 1!');
valid = false;
}
try {
var sum2 = (parseInt(number[13]) * 7) +
(parseInt(number[14]) * 3) +
(parseInt(number[15])) +
(parseInt(number[16]) * 7) +
(parseInt(number[17]) * 3) +
(parseInt(number[18]));
alert(((sum2 % 10).toFixed(0)));
var checkDigit2 = ((sum2 % 10).toFixed(0));
if ((number[19]) === ("" + checkDigit2)) {
alert('Our Checkdigit2 is valid', checkDigit2);
valid = true;
}
} catch (e) {
alert('Fail for check 2!');
valid = false;
}
try {
var sum3 = (parseInt(number[21]) * 7) +
(parseInt(number[22]) *3) +
(parseInt(number[23])) +
(parseInt(number[24]) * 7) +
(parseInt(number[25]) * 3) +
(parseInt(number[26]));
alert(((sum3 % 10).toFixed(0)));
var checkDigit3 = ((sum3 % 10).toFixed(0));
if ((number[27]) === ("" + checkDigit3)) {
alert('Our Checkdigit3 is valid',checkDigit3);
valid = true;
}
} catch (e) {
valid = false;
}
alert('All Good DUde!');
return valid;
}
Here is the way to do it.
I have not thrown any error, only error can be if the number is not parseable and so you can throw it if you like else if your sum checks can validate that should be good enough
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
var valid = false;
//try{
var sum1 = returnSum(number,[0,1,2,3,4,5,6,7,8],[7,3,1,7,3,1,7,3,1]);
var sum2 = returnSum(number,[13,14,15,16,17,18],[7,3,1,7,3,1]);
var sum3 = returnSum(number,[21,22,23,24,25,26],[7,3,1,7,3,1]);
/*
//only if you are throwing err
}catch(e){
valid = false;
}
*/
if (number[9] === sum1 && number[19] === sum2 && number[27] === sum3) {
console.log(sum1 +'|' + sum2 + '|' + sum3);
valid = true;
}
console.log('All Good DUde!');
return valid;
}
function myParse(n){
return (isNaN(parseInt(n,10))) ? -1 : parseInt(n,10);
}
function returnSum(n,ind,mul){
var acc = 0;
var pNum = 0;
for(var i=0; i<ind.length; i++){
pNum = myParse(n[ind[i]]);
if(pNum == -1){
pNum=0;
//throw 'error';//if you really want to throw error on not a number / or your number should fail
}
acc += pNum * mul[i];
}
return (acc%10).toFixed(0)+'';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3> Sample test number to use -- copy and paste should work </p=h3>
<p>487013675311199070109160101300</p>
<input id="searchTxt" placeholder="add numbers together">
<div id='numberValue'>Number goes here</div>
Cheers. joy
From experience, you may want to separate as much math as possible in your try block. JavaScript has a weird way of handling variables and may not be doing what you think it is.

Use jquery or javascript to add commas to disabled field

I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.

Trying to add and remove items from an array

The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
printList = function() {
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
document.write(i + ":");
document.write(myList[i] + "<br/>");
};
document.write("<br/><br/>");
};
// initial list
var myList = new Array ();
if (myList.length === 0) {
document.write("I have " + myList.length + " item in my list. It is: <br/>");
}
else {
document.write("I have " + myList.length + " items in my list. They are: <br/>");
}
printList();
var continueAdding = "yes";
var askToContinue = "";
while (continueAdding === "yes") {
// loop
var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
switch (askUser) {
case "A": { // add an user specified item to the list
var addItem = prompt("Add something to the list");
myList.push(addItem);
printList();
break;
}
case "R": { // remove an user specified item from the list
var removeItem = prompt("what do you want to remove?");
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
break;
}
if (myList.length === 0) {
myList[0] = "Nada";
}
};
printList();
break;
}
default: {
document.write("That is not a proper choice.");
}
};
askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
if (askToContinue === "Y") {
continueAdding = "yes";
}
else {
continueAdding = "no";
}
}
Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
break;
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
}
};
if (myList.length === 0) {
myList[0] = "Nada";
}
Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.

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

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

Categories