Javascript code to convert serial numbers converted from PHP - javascript

These two Javascript functions are supposed to convert serial numbers (2-9999) for example into a number , but the functions below are not working for some reason .. they were originally written in PHP ... Works in PHP but not for Javascript.
<html>
<head>
<script type="text/javascript">
function my_isnum(str, negative=false, decimal=false)
{
var has_decimal = false;
var len = strlen(str);
if (len > 0) {
var valid = true;
for (var i=0; valid && i < len; i++) {
if (!(str[i] >= "0" && str[i] <= "9")) {
if (str[i] == "-") {
if (!negative || i != 0) {
valid = false;
}
} else if (str[i] == ".") {
if (!decimal || has_decimal) {
valid = false;
}
} else {
valid = false;
}
}
}
} else {
valid = false;
}
return valid;
}
function esn_to_num(esn) {
var tmp = [];
if ((tmp = esn.split("-")) {
if (tmp.length == 2
&& my_isnum(tmp[0])
&& my_isnum(tmp[1])
) {
esn = ((tmp[0] << 23) | tmp[1]);
} else {
esn = -1;
}
} else {
esn = -1;
}
return esn;
}
alert(2-9999);
</script> </head>
</html>
Original PHP functions
<?php
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
?>

There is no such thing as strlen in Javascript. Use str.length instead.
Also, as Jason Sperske suggested below, change this:
function my_isnum(str, negative=false, decimal=false)
To this:
function my_isnum(str, negative, decimal)
{
if (typeof negative == "undefined") negative = false;
if (typeof decimal == "undefined") decimal = false;
....
}

These two javascript functions are supposed to convert serial numbers (2-9999) for example into a number.
Why not just get rid of the - and parse as a decimal number?
function padToFourDigits(_, digits) {
return "0000".substring(digits.length) + digits;
}
function serialToNum(serialNumStr) {
return +(serialNumStr.replace(/-(\d{1,4})/g, padToFourDigits));
}
Then
serialToNum('2-9999') === 29999
serialToNum('2-999') === 20999

Related

How to check if switch is true or not to hide the div?

I have some problem when I check the function validation, I need when checking all the cassis is true hide the parent div * errors message *
var error_pass = false;
$('#pass').focusout(function(){
check_pass();
error_pass = false;
if(error_pass !== true){
console.log('its showing!');
}else{
$('.test').fadeOut('522');
}
});
function check_pass() {
var fpass= $('#pass').val();
switch(error_pass = true){
case(fpass.length < 6 ? $('#pass-error-message3').css('color','red'):$('#pass-error-message3').css('color','green') ):
$('#pass-error-message3').show();
case(fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1 ? $('#pass-error-message4').css('color','red') : $('#pass-error-message4').css('color','green')):
$('#pass-error-message4').show();
case(fpass.search(/\d/) == -1 ? $('#pass-error-message2').css('color','red'):$('#pass-error-message2').css('color','green')):
$('#pass-error-message2').show();
default:break;
}
}
Use if else statements like this
function validation() {
var error = false;
if (fpass.length < 6) {
error = true;
$('#pass-error-message3').css('color', 'red').show();
} else {
$('#pass-error-message3').css('color', 'green');
}
if (fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1) {
error = true;
$('#pass-error-message4').css('color', 'red').show();
} else {
$('#pass-error-message4').css('color', 'green')
}
if(fpass.search(/\d/) == -1){
error = true;
$('#pass-error-message2').css('color','red').show();
}else{
$('#pass-error-message2').css('color','green');
}
if(error === false){
hideParentDiv(); // Here hide the div
}
}
Much cleaner approach

Using for loop to order dependency

var input = [ "KittenService: ", "Leetmeme: Cyberportal", "Cyberportal: Ice", "CamelCaser: KittenService", "Fraudstream: Leetmeme", "Ice: "];
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
return;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
if(output.indexOf(packageName) > -1) {
continue;
}
else {
output.push(packageName);
}
}
}
else if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
return output.join(', ');
}
valid(input);
I am trying to figure out way to make the output to become
"KittenService, Ice, Cyberportal, Leetmeme, CamelCaser, Fraudstream"
Right it logs
'KittenService, Cyberportal, Leetmeme, Ice, CamelCaser, Fraudstream'
I am not sure how to make all the input with dependencies to pushed before input with dependencies.
Problem was just that you were returning if no package name instead of using a continue.
var input =[ "KittenService: CamelCaser", "CamelCaser: " ]
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
continue;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
}
return output;
}
console.log(valid(input));

I don't want to allow a 9 digit number in my textbox which is in format:123-12-1234 or 123456789

I am trying like this:
function k(){
var x = $('#textArea').val();
for (i = 0; i < x.length; i++)
{
if(x[i].match(/^[0-9]/))
{
if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
{
if(x[i+11].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
{
if(x[i+9].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
return 'true';
}
Or simply
var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
Or if you only want to allow - and digits
var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length )
{
return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
or using pure regexp
to match the 123-45-678 and 12345678 formats:
var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
return true;
} else return false;
to match any number less then 9 digits:
var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
return true;
} else return false;

Why am I getting an undefined alert when entering a number into my array?

When I input numbers into the array, I get two alerts: a "number" alert, and then an "undefined" alert. I don’t know how to fix this.
This is my JavaScript code:
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if (elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number'. myStuff);
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for (var i = 0; i < myStuff.length; i++) {
sum += myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n')); {
if (myStuff == [])
{
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while (sorted) {
sorted = false;
for (var i = 0; i < myStuff.length - 1; i++) {
if (myStuff[i] < myStuff[i + 1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i + 1];
myStuff[i + 1] = temp;
sorted = true;
}
}
}
}
The following line evaluated to undefined:
alert('Thank You for entering a valid number'. myStuff);
Do you maybe mean?:
alert('Thank You for entering a valid number' + myStuff);

Appending conditions in a numerical loop (JavaScript)

I have four IF statements, is it possible to rewrite this into a neater loop, where the [i] may be '4' or higher.
if (typed.length == 1 && c.charAt(0) == typed[0]) {
//something ;
return false;
}
if (typed.length == 2 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1]) {
//something ;
return false;
}
if (typed.length == 3 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]) {
//something ;
return false;
}
if (typed.length == 4 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]
&& c.charAt(3) == typed[3]) {
//something ;
return false;
}
Looks to me like something like this should to it:
if (c.substr(0, typed.length) == typed)
Possibly typed.join() if typed is an array.
Try this
for(var x=0; x<typed.length; x++)
{
if(c.chatAt(x)!=typed[x]) { return false; }
}
return true;
for (var i=1; i<=4; ++i){
if (typed.length!=i) continue;
var OK = true;
for (var j=0;j<i;++j){
OK = OK && (c.charAt(0)==typed[j]);
}
if (OK){
// something
return false;
}
}
Forget about two nested loops, or assuming c and typed are "ordered", just look for the char in c
for (var i=0; i<typed.length; i++) {
if (c.indexOf(typed.charAt(i)) >= 0) { // or c.indexOf(typed.charAt(i)) == i
return false;
}
}
return true;

Categories