Check values in a form (Javascript) - javascript

I've five variables in a form, for simplicity I named them A, B, C, D and E.
In order to submit the form (A or (B or C)) and (D or E) must have a value (I hope it's clear :P).
I've tried with
if ((A == "" || (B == "" || C == "")) && (D == "" || E == "")) {
alert ("Error!");
} else {
form.submit();
}
But it doesn't work in every case. For example, if A, B and C have a value, the form is submitted even if neither D or E have values.
Thank you for the help!

If you have all strings, you could just reverse the condition and check all with logical AND and one OR.
var a = '', b = '', c = '', d = '', e = '';
if (a && b && c || d && e) {
console.log('form.submit();');
} else {
console.log('Error!');
}
Why it works:
given
(A == "" || (B == "" || C == "")) && (D == "" || E == "")
simplified A == "" is equivalent to !A
(A == "" || B == "" || C == "") && (D == "" || E == "")
(!A || !B || !C) && (!D || !E)
De Morgan's laws !(a && b) = !a || !b or !(a || b) = !a && !b
(!A || !B || !C) && (!D || !E)
!(A && B && C) && !(D && E)
!((A && B && C) || (D && E))
operator precedence
!(A && B && C || D && E)
now switch/negate then <-> else
A && B && C || D && E

if (A == "" || B == "" || C == "" && (D == "" || E == "")) {
alert ("Error!");
} else {
form.submit();
}

You need to change your logic to:
if ((A != "" || (B != "" || C != ""))
&& (D != "" || E != "")) {
form.submit();
} else {
alert ("Error!");
}
The alternative is to do it like so:
if ((A == "" && (B == "" && C == ""))
|| (D == "" && E == "")) {
alert ("Error!");
} else {
form.submit();
}
Edit: the first snippet can be refactored to the following:
if ((A || (B || C )) && (D || E )) {
form.submit();
} else {
alert ("Error!");
}
And the same can be done with the second snippet with the NOT operator !.

I updated the code a bit. I think this should work for you.
function isNonEmpty(string) {
//returning the string's truthiness value
return string.trim() ? true : false;
}
//change these values around to make sure the logic is correct
var A = "cat",
B = " ",
C = "dog",
D = "",
E = " turtle";
//almost exactly what you have just calling a function for neatness
if ((isNonEmpty(A) || isNonEmpty(B) || isNonEmpty(C)) &&
(isNonEmpty(D) || isNonEmpty(E))) {
console.log("Valid form. Time to submit!");
} else {
console.log("Invalid form. Please check your values!");
}

Related

Max Value with decimal 99.999 HTML block input

I'm trying to make the input takes only the value 99.999. I don't want to use MaxLength because it would not calculate the length of the decimal digits. I don't want to use any other functions that erase when it doesn't match a specific regex. I want it to stop it in the input.
function IsCurrencyNoMinus1 (e, thisobj, min, max) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (keyCode == 46) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val();
if (ret && (keyCode == 45) && ((thisobj.selectionStart != 0) || (inStr.indexOf('-') != -1)))
ret = false;
if (ret && (keyCode == 46) && (inStr != '' && inStr.indexOf('.') != -1) && !(Math.abs(thisobj.selectionStart - thisobj.selectionEnd) == inStr.length)) {
ret = false;
}
var dotPos = (inStr.indexOf('.') != -1) ? inStr.indexOf('.') : inStr.length;
inStr = inStr.replace(/\,/g, '');
var parts = inStr.split('.');
var maxParts = max.toString().split('.');
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57))) {
if ((parts[0].length >= maxParts[0].length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)
&& (thisobj.selectionStart <= dotPos)) {
ret = false;
}
if (ret && (parts[1] != undefined && parts[1].length >= 2) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0)
&& (thisobj.selectionStart > dotPos) && (thisobj.selectionStart <= dotPos + 3))
ret = false;
var firstPos = thisobj.selectionStart < thisobj.selectionEnd ? thisobj.selectionStart : thisobj.selectionEnd;
if (ret && (parts[0].length >= maxParts[0].length) && (parts[1] != undefined && parts[1].length >= 1)
&& ((dotPos - firstPos == 0 && Math.abs(thisobj.selectionStart - thisobj.selectionEnd) < 4)
|| (dotPos - firstPos == 1 && (Math.abs(thisobj.selectionStart - thisobj.selectionEnd) >= 2 && Math.abs(thisobj.selectionStart - thisobj.selectionEnd) < 4))))
ret = false;
}
if (Number(inStr) > max) {
thisobj.value = '';
ret = true;
}
if (Number(inStr) < min) {
thisobj.value = '';
ret = true;
}
// var re = new RegExp(/^\(?-?[0-9]{0,12}(\.[0-9]{0,2})?\)?$/)
// if (!re.test(inStr)) {
// thisobj.value = ""
// }
return ret
}
I found the solution! Please check the code below in case someone needs it.
function Format3DigitDecimal(e, thisobj, min, max)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))
var inStr = $(thisobj).val()
inStr = inStr.replace(/\,/g, '')
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
{
if ((inStr.length == 2) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
{
ret = false
}
}
return ret
}

Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn) in zepto.js - event.js?

In event.js, to judge the same handler, here is code:
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn)
Here is the source code of zid
var _zid = 1
function zid(element) {
return element._zid || (element._zid = _zid++)
}
if I have to judge two functions, a === b is enough
why to use zid(a) === zid(b)? Maybe some trap?
I don't know why?
Here is the source code of zepto.js event.js: https://github.com/madrobby/zepto/blob/master/src/event.js

How to make a maintainable list of conditions

I have this code, which in time could be hard to read and maintain - numbers could come and go. How do I make this into an easy accessible maintainable list of conditions? Should I use an Array or something else?
var cs = 123456; //Some integer
if (cs >= 320000
&& cs <= 320026
|| cs == 320141
|| cs == 320143
|| cs == 320145
|| cs == 320147
|| cs == 320149
|| cs == 320151) {
new = 'Y';
} else if (cs >= 320100
&& cs <= 320112
|| cs >= 320114
&& cs <= 320116
|| cs >= 320123
&& cs <= 320128
|| cs == 320142
|| cs == 320144
|| cs == 320146
|| cs == 320148
|| cs == 320150
|| cs == 320152) {
new = 'N';
} else {
new = 'Unknown';
};
Yes, what you need is a array and an indexOf method.
Example:
if (cs >= 320000 && cs <= 320026 || $.inArray(value, valuesarray) > -1) {
--
}
https://stackoverflow.com/questions/16910305/if-or-shorter-way/16910313#16910313

Javascript alert on dropdown menus?

I have a javascript alert on my form here - http://investing.uglyopportunities.com/opportunity/ I have the javascript function working correctly for my form. Except I also want the javascript to alert when the user doesn't select from either of the two drop down menus. I really don't have much experience at all with javascript, so keep that in mind! Here is my current code. I really appreciate any help
<script type="text/javascript">// <![CDATA[
function validateForm() {
var a = document.forms["myform"]["inf_field_FirstName"].value;
var b = document.forms["myform"]["inf_field_Email"].value;
var c = document.forms["myform"]["inf_field_Phone1"].value;
var e = document.forms["myform"]["inf_field_City"].value;
var f = document.forms["myform"]["inf_field_State"].value;
var g = document.forms["myform"]["inf_field_PostalCode"].value;
if (a == null || a == "" || a == "First Name Here") {
alert("Please enter your First Name!");
return false;
}
if (c == null || c == '' || c == "Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
if (e == null || e == '' ||e == "City") {
alert("Please insert your city");
return false;
}
if (f == null || f == '' || f == "State") {
alert("Please insert your state ");
return false;
}
if (g == null || g == '' ||g == "Postal Code" || c.length < 5) {
alert("Please insert your postal code");
return false;
}
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
}
// ]]>
</script>
if(document.getElementById('inf_custom_LevelofInterest').value == '' || document.getElementById('inf_custom_Doyouhavemoneytoinvest').value == ''){
alert('please select ...');
return false;
}

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories