Solved

JavaScript validation

Posted on 2012-04-13
8
302 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
  • 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
 

Author Closing Comment

by:vickyjava
ID: 37846210
thank you sir!
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…

743 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now