Solved

JavaScript validation

Posted on 2012-04-13
8
309 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

809 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