Solved

JavaScript validation

Posted on 2012-04-13
8
323 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

751 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