How to change this IF to allow selection between two numbers only? - javascript

I am using a jQuery script and the main part is below. It allows me to select up to 4 items. Until there are 5 selections made, there is an error message.
How can I change this so that the error message appears if the choices are less than 2 and more than 5, and the success message is shown when the choices are between them?
if ($(this).multiselect("widget").find("input:checked").length > 5) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}

You can get the number of checked items in to a local variable and then use a compound if statement that does multiple comparisons on it:
var checkedItemsLength = $(this).multiselect("widget").find("input:checked").length;
if(checkItemsLength < 2 || checkItemsLength > 5 ) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}

function doSomeChecking() {
// assuming 'warning is a reference to some div or span
var warning = $('#warning');
var numChecked = $(this).multiselect("widget").find("input:checked").length;
if (numChecked > 5) {
warning.addClass("error").removeClass("success").html("You cannot check more than five boxes!");
return false;
} else if (numChecked < 2) {
warning.addClass("error").removeClass("success").html("You must check at least two boxes.");
return false;
}
warning.addClass("success").removeClass("error").html("Life is good.");
return true;
}

var selections = $(this).multiselect("widget").find("input:checked");
if(selections.length < 2) {
warning.addClass("error").removeClass("success").html("You have to check atleast two checkboxes!");
return false;
} else if (selections.length > 5) {
warning.addClass("error").removeClass("success").html("You can not check more then five checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}

if(foo < 2 || foo > 5){
//do something
}else {
//do something else
}

Related

Check even number in Angular

I am learning Angular right now and i have an error. I have a button and when i click this button i increase this variable by 1.
checkNumber=0;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
}
Now i want to show if the current "checkNumber" is even or not so i created the following variable:
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven == false;
}
else{
this.isEven == true;
}
console.log(this.isEven);
}
The problem is, that this function alway returns false no matter what the actual number is. (I trigger the increaseLength() function with a button click).
When you want to assign value to a variable you're writing only one = and not ==, when you want to check if it equals to something then use ==
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven = false;
}
else{
this.isEven = true;
}
console.log(this.isEven);
}
This should work but I prefer to use this function, much more shorter:
function isEven(n) {
return n % 2 == 0;
}
If it returns true so it will be even if not it will be odd so just to add one if.
this.isEven == false; This should be an assignment here , rather you are checking for condition in your code. It should be :
this.isEven = false;
and
this.isEven = true;
It should be an assignment to this.isEven:
isEven = false;
increaseLength(event: any){
this.checkNumber = this.checkNumber+1;
if(this.checkNumber % 2 != 0){
this.isEven = false;
}
else{
this.isEven = true;
}
console.log(this.isEven);
}
Also you can massively simplify your code:
isEven = false;
increaseLength(event: any) {
this.checkNumber += 1;
this.isEven = this.checkNumber % 2 === 0;
console.log(this.isEven);
}

How to make usernames banned on a website

How can I find out if a text input is a certain text?
I tried this
<script>
var b = document.getElementById('button')
var u = document.getElementById('username')
var p = document.getElementById('password')
var bannedUsers = ["user1012"];
b.onclick = function() {
if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
location.href = "";
};
if(u.value.length > 20) {
return alert('Username needs to be below 20 characters.')
} else if(u.value.length < 3) {
return alert('Username needs to be above 2 characters')
}
if(p.value.length < 6) {
return alert('Password needs to be over 6 characters.')
}
if(u.value === bannedUsers) {
return alert('That username is banned.')
}
}
</script>
But it ended up just taking me to the page instead of saying "This username is banned"
You need to use the includes method.
bannedUsers.includes(u.value)
what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'
You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (bannedUsers.includes(u.value) {
return alert('That username is banned.')
}

I have a javascript that checks if my form is valid and it stops checking after a certain field

So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.

Simplifying IF/ELSE IF/ELSE Block

I'm creating my own validation code. I need to separate the if statements per input box for the error to show at the same time. I noticed that if it's on same if block, only the first error will show. Any way to simplify my code?
flag = 0;
//first if
if (first_name.length == 0) {
flag = 0;
$("label[for='firstname'").text('This field is required').css("display", "inline-block");
} else if (!first_name.match(name_regex)) {
flag = 0;
$("label[for='firstname'").text('Firstname must be composed of letters only').css("display", "inline-block");
} else if (first_name.length < 3) {
flag = 0;
$("label[for='firstname'").text('3 letters are required for lastname').css("display", "inline-block");
} else {
flag = +1;
$("label[for='firstname'").hide();
}
//second if
if (last_name.length == 0) {
flag = 0;
$("label[for='lastname'").text('This field is required').css("display", "inline-block");
} else if (!last_name.match(name_regex)) {
flag = 0;
$("label[for='lastname'").text('Lastname must be composed of letters only').css("display", "inline-block");
} else if (last_name.length < 2) {
flag = 0;
$("label[for='lastname'").text('2 letters are required for lastname').css("display", "inline-block");
} else {
$("label[for='lastname'").hide();
flag += 1;
}
//third if
if (validateEmail(email)) {
if (data.result) {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Email exists').css("display", "inline-block");
} else {
$("input#userEmail").css("border-color", "#e3e3e3");
$("label[for='email'").hide();
flag += 1;
}
} else {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Please input a valid email address').css("display", "inline-block");;
}
//fourth if on verification success
if (flag == 3) {
alert("All validation succeded!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Just extract it into a function:
function validate(inputName, labelName, minLetters, regex){
const el = $(inputName);
const label = $(labelName);
if(!el || !!label) throw "validate: el not found";
if(!el.val()){
label.text("You need to fill in this!");
return false;
}
if(regex && !el.val().test(regex)){
label.text("The input contains invalid chars!");
return false;
}
if(minLetters && el.val().length < minLetters){
label.text("to short!");
rerurn false;
}
return true;
}
I would suggest to make the validation routine more generic. Please see following solution (note: untested):
function validate(funcName, minLength) {
if (this[funcName].length == 0) {
$("label[for='"+funcName+"'").text('This field is required').css("display", "inline-block");
} else if (!this[funcName].match(name_regex)) {
flag = 0;
$("label[for='"+funcName+"'").text(funcName +' must be composed of letters only').css("display", "inline-block");
} else if (this[funcName].length < minLength) {
$("label[for='"+funcName+"'").text(minLength + ' letters are required for ' + funcName).css("display", "inline-block");
} else {
$("label[for='"+funcName+"'").hide();
return true;
}
return false;
}
if (validate("firstname", 2)
&& validate("lastname", 3)
&& validateEmail(email)
) {
// everything seems to be OK.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My approaches will be :
Have individual If blocks for each validations by which all the validations will be checked. And build/append the validation error message on each check.
Write if else blocks within a function. That function can be called for each fields being validated. And the function will return validation error message for each invokation which can be appended into a single string.

How Would I Alter This Javascript Code to validate the data

What would I need to add in order for this to validate according to how many checkboxes have been selected? I want the user to select at least two checkboxes before submission of data. Here is my Javascript code:
<script type="text/javascript" language="JavaScript">
function checkCheckBoxes(theForm) {
if (
theForm.Conservatives.checked == false &&
theForm.Labour.checked == false &&
theForm.LiberalDemocrats.checked == false)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
</script>
The current Javascript code only validates if any checkboxes have been selected or not, but I want it to validate for two checkboxes.
Just count how many are checked and see if it's less than 2.
function checkCheckBoxes(theForm) {
var cnt = 0;
if (theForm.Conservatives.checked) ++cnt;
if (theForm.Labour.checked) ++cnt;
if (theForm.LiberalDemocrats.checked) ++cnt;
if (cnt < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
As long as you're only worried about those three checkboxes and you don't want to use a JavaScript library, the easiest thing I can think of would be:
var checkedBoxes = [];
if(theForm.Conservatives.checked)
checkedBoxes.push(theForm.Conservatives);
if(theForm.Labour.checked)
checkedBoxes.push(theForm.Labour);
if(theForm.LiberalDemocrats.checked)
checkedBoxes.push(theForm.LiberalDemocrats;
// two or more boxes are checked
if(checkedBoxes.length < 2){
alert('Choose at least two parties.');
}
else {
// Do stuff with checkedBoxes.
}
This method will not only give you the Count of the number of checked items but will also allow you to access only the checked boxes later in your code if needed.
You can do:
if (theForm.Conservatives.checked +
theForm.Labour.checked +
theForm.LiberalDemocrats.checked) < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
function checkCheckBoxes(theForm) {
var opts = ["Conservatives","Labour","LiberalDemocrats"],
selected = 0;
for (var i = 0; i < opts.length; i++) {
if (theForm[opts[i]].checked)
selected++;
}
if (selected < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
function checkCheckBoxes(theForm) {
if(theForm.Conservatives.checked + theForm.Labour.checked + theForm.LiberalDemocrats.checked > 1)return true;
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
}
function checkCheckBoxes(theForm) {
var checkboxes = [theForm.Conservatives, theForm.Labour, theForm.LiberalDemocrats];
var checked = 0;
checkboxes.forEach(function(el){
if (el.checked) checked++;
});
if (checked < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}

Categories