Solved

JavaScript validation

Posted on 2012-04-13
8
320 Views
Last Modified: 2012-04-14
help required on JavaScript for validating the Amount

I need front end validation for a text box

 

1.       It should not allow character, special symbols etc.. as usual

2.       It should allow numbers

3.       the maximum precision is (5,2) e.g. 12345.12

4.       it should allow like 0,1,2,3…. .1,.2,.33,….0.1,02…. 1.1,1.3,……. 12.11,32.45,…………. Up to 12345.12

5.       it should not accept like 1.3455, 123456.12, .34344
0
Comment
Question by:vickyjava
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37845725
This is not clear
0,1,2,3…. .1,.2,.33,….0.1,02…. 1.1,1.3,……. 12.11,32.45,…………. Up to 12345.12

Do you mean

0
1
2
3
.1
.2
.33
0.1
0.2  (was 02!)
1.1
1.3
12.11
32.45
up to 99999.99 (was 12345.12)

?
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 37845752
We can take this

http://www.mredkj.com/tutorials/validate2.html

and add number of digits before the point DEMO :

window.onload=function() {
    var fld = document.getElementById("numberfield");
    fld.onblur=function(event) {extractNumber(this,2,true);}
    fld.onkeyup=function(event) {extractNumber(this,2,true);}
    fld.onkeypress=function(event) {return blockNonNumbers(this, event, true, true, 10000); }
}

// this is the js file you can externalise        
        
// version: beta
// created: 2005-08-30
// updated: 2005-08-31
// mredkj.com
// maxVal added by mplungjan 2012-04-14

function extractNumber(obj, decimalPlaces, allowNegative, maxVal)
{
    var temp = obj.value;
    
    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;
   
    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }
    
    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }
    
    obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative, maxVal)
{
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
        
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }
    
    if (isNaN(key)) return true;
    
    keychar = String.fromCharCode(key);
    
    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    reg = /\d/;
    var val = obj.value;
    var isFirstN = allowNegative ? keychar == '-' && val.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && val.indexOf('.') == -1 : false;
    
    if (maxVal && !isNaN(val) && parseFloat(val)>maxVal) return false;
    return isFirstN || isFirstD || reg.test(keychar);
}
        

Open in new window

0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 37845898
/^([0-9]{0,5}\.[0-9]{0,2}|[0-9]{1,5})$/.test(your_number);

// matches:
12345.12
12345.
12345
.12
// fails for:
12345.123
123456.12
-1234.12
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Closing Comment

by:vickyjava
ID: 37846210
thank you sir!
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 37846222
may I ask what the advantage of ~100 lines of code compared to a simple easy to read single line regex is?
@mplungjan, no offence meant :)
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37846235
You provided a regex that possibly can be used in the validation - missed the sign if needed btw

I provided a complete solution that blocks the user from inputting the wrong number in the first place.
Most of the code I posted is event handling - the rest makes it easy to change decimals and values allowed
The code can be reduced if one adds your regex
I assume the asker is not up to that task, no offence nor any taken;)
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 37846282
yes I see the "handling code", and the missing sign is simply:
   /^[+-]?([0-9]{0,5}\.[0-9]{0,2}|[0-9]{1,5})$/.test(your_number);

> ... that blocks the user from inputting the wrong number ...
hmm, is it really worth writing such complex code if the same result could be done very simple in the onsubmit event?
the values need to be checked sever-side anyway

sorry for being pedantic, no answer expected :)
KISS - keep it simple stupid
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 37846307
The asker wanted the field to not accept wrong input. I provided that answer.
I could equally have provided an onsubmit test but did not see that in the question
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It is a general practice to get rid of old user profiles on a computer  in a LAN environment. As I have been working with a company in a LAN environment where users move from one place to some other place at times. This will make many user profil…
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn how to dynamically set the form action using jQuery.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question