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
Solved

JavaScript validation

Posted on 2012-04-13
8
314 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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

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

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

808 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