I am creating a voting system webpage using Javascript. There are several things the user must input before beginning the vote, such as candidates, number of people voting, etc. I have created a function for each one, but when I attempted to add some validating if statements to my enterCandidate function, it would not register an error when the user left the box blank. Here is the function code:
var enterCandidate = prompt("Please enter a candidate");
for (let i = 0; i < enterCandidate.length; i++){
if (isNaN(enterCandidate.charAt(i)) || enterCandidate.charAt(i) == ' '){
if (!enterCandidate.length == 0){
candidates.push(enterCandidate);
console.log(enterCandidate);
candidate1 = candidates[0];
candidate2 = candidates[1];
candidate3 = candidates[2];
candidate4 = candidates[3];
candidate5 = candidates[4];
candidate6 = candidates[5];
} else {
alert('Please do not leave the box blank.');
}
} else {
alert('Please enter a name, without symbols or numbers.');
}
}
}
The part I am having an issue with is the second if statement, where I used !enterCandidate.length == 0. This should only return true if the user has inputted something but instead it returns false and moves to the else alert 'Please do not leave the box blank'. I am aware that even if this code worked, it would allow people to enter just spaces - I am not really sure how to tackle that without registering errors if people entered full names.
Related
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
The below java script condition works in two condition but one of the condition is not working properly.
Page has a field which allow user to enter either without wildcard or with wild card with two characters For eg: PA% or PAGTHYUR
If the user enter PAGTHYUR in the Search Field still the else condition alert is calling "There is delay processing times for broad wildcard searches" instead of directly submit the "searchType".
How to avoid the else alert if the user enter direct value(for eg:PAGTHYUR)
My Script is as below:
if(manufNo!="") {
var strLen = manuNo;
var wild = "%";
if(strLen.indexOf(wild) != -1 && strLen.indexOf(wild) < 2) {
alert("Enter atleast two characters before wildcard");
return false;
} else {
alert ("There is delay processing times for broad wildcard searches");
}
searchType = "manufNo";
}
Thanks in advance
Add an extra else if in case there is no wildcard, you just gotta figure out what you want to happen in that case:
if(manufNo!=""){
var strLen = manuNo;
var wild = "%";
if (strLen.indexOf(wild) === -1) {
//code for what happens when there is no wildcard
// potentially nothing?
} else if (strLen.indexOf(wild) < 2){
//well place wildcard
alert("Enter atleast two characters before wildcard");
return false;
} else {
//badly placed wildcard
alert ("There is delay processing times for broad wildcard searches");
}
searchType = "manufNo";
}
My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");
I'm trying to make a verification that an input text has an email format after clicking submit buttom and calling a js function. The first problem i encounter is that after some tests, i've seen that it doesnt enter the called function. After this, i think everything should be ok, but just in case in order to not post 2 almost equal questions within minutes, ill include the most important part.
Summarizing, it should check:
-The email field is not null
-The email field has an # (without taking into account order etc)
Then it should tell if it found any problem, if not leave everything unchanged
I hope i made my point, if not i can try to explain it again..
<input type="text" name="email" id="email">
<input type="submit" onclick=" proceed()"/>
<script>
proceed(){
var email= document.getElementById('email').value;
var problems;
if (email == ""){
problems = "Empty variable \n";
}
var noat = true;
for (int i=0; email.length; i++){
if (email.charAt(i) == "#"){ //Compare each character
noat=false;
break;
}
}
if (email=="" || noat=true){
problems += "No # \n"
alert(problems);
}
}
</script>
<form onsubmit="return proceed();">
<input type="text" name="email" id="email">
<input type="submit" />
</form>
<script>
function proceed() {
var email = document.getElementById('email').value;
var problems = "";
if (email == "") {
problems = "Empty variable \n";
}
var noat = false;
if (email.indexOf("#") == -1) noat = true;
// for (int i=0; i< email.length; i++){
// if (email.charAt(i) == "#"){ //Compare each character
// noat=false;
// break;
//}
if (email == "" || noat == true) {
problems += "No # \n";
alert(problems);
}
if (problems == "")
return true;
else
return false;
}
</script>
Instead of using onclick, i think you should use onsubmit and instead of comparing each character for # symbol, you should use email test regular expressions.
there are plenty of those online, just google.
sample regular expressions
Well I was about to write this myself but I happened to have found it like 4 hours ago. This will help you.
<script>
function proceed()
{
var email = document.getElementById("email").value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length)
{
alert("Not a valid e-mail address");
return false;
}
};
</script>
<form onsubmit="proceed();">
<input type="text" name="email" id="email" />
<input type="submit" />
</form>
Your code had a lot of typos, just take your time when writing. This is from w3schools
This question has already been marked as answered, but I feel that there a few key takeaways / learning points from the question, so i've added my input below, fwiw.
Right now the code in your question starts off with proceed() { ... }. You should change this to function proceed() { ... } to make it a proper function declaration
It's a good habit to define your variables at the top of your scope in which they are being used. As of now you have the email and problems vars declared next to each other, and that's good. However, var noat is all by itself a few lines down. Moving it up to the other declarations helps the reader of your code understand which variables are to be used in this function
On the fourth line of your function you check to see if email is an empty string. If it is, you set the problems variable. But if it's empty, we can stop where we are. You can just return problems; and be done with the function.
It's already been pointed out, but email.indexOf("#") uses the native JS method to do what you're doing in the string iterator.
for(int i=0; ...) I thought the int i =0 looked funny, so I tried typing it into the javascript console on my browser. I got an error. You can change this to for(var i = 0; ...) for the correct syntax.
Later on in the function we ask if email is empty again: if(email == ""). But we've already asked this question, and would have exited the function if it was true. We can't have an # symbol in the string if the string is empty.
This has been mentioned before but you probably want to use a regular expression to check the email.
Next we have noat = true. This will actually always evaluate to true because the result of the assignment is truthy. You're setting the value of noat to true, and javascript is like "Cool awesome looks good to me". It doesn't check if noat was originally set to true or false.
I've created and tested a jsfiddle that follows most of these recommendations. It also shows a way to make the code more concise and achieve a similar goal. Sorry if this comes off as too preachy/know-it-all, I definitely don't. This question piqued my interest and I had to respond!
window.proceed = function () {
var email = document.getElementById('email').value;
if (email == "") {
alert("Empty variable \n");
} else if (email.indexOf("#") == -1) {
alert("No # \n");
} else return true;
}
jsfiddle
var val_em=document.add_indus_detail_form.txt_email.value;
var atpos=val_em.indexOf("#");
var dotpos=val_em.lastIndexOf(".");
if(val_em!='')
{
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=val_em.length)
{
alert("Not a valid e-mail address");
return false;
}
}
i use this condition to check the email validation that user enters in the textbox how i can validate it like it allows 3 or 4 or any specific numbers of dot allow (ex abc.abc.abc.abc#abc.abc.com) before and after the # but do not allow that dots together (ex: abc#abc...com). also do not allow the spaces in email how it will be have you any idea for this type of validation..
I would suggest a regex for this
function validateEmail(email){
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(email);
if(!valid) {
return false;
} else {
return true;
}
}
call the function validateEmail whenever you need....
Validations in JavaScript are useless. The user can turn off JS or maybe you encounter a browser who cant even understand JS. This makes your page vulnerable to attacks. So NEVER use JS for validating user inputs.
What you want is RegEx or many if-conditions together with string-functions. My approach: Use a For-Loop, go through the string one by one, check the current character and the one after it. Like this:
for($i = 0; $i < strlen($string); $i++) {
if(substr($string, 0, 1) == '.' {
//do something
}
}