field validation as float with certain integer and certain decimal

S

SAN CAZIANO

i have to do in the onkeypress or in onchange the float (real) field
validation

I try something:

function ValidaCampo(nomeCampo,TotInteri,TotDecimali)
{
DecimalPos=NomeCampo.value.Indexof(',');
Lungh=TotInteri+TotDecimali+1; //sum the ineger + decimal +
decimal separator


if ((window.event.charcode==',') && (DecimalPos>-1))
//i think exist a decimal separator so i don't add any other
else
if (DecimalPos<>TotInteri+1)
//i haven' t insert too much integer
else
if i haven't add any decimal, i add a separator with two zero value
else
if nomecampo.length<>Lungh
//error

}
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 13
Oct 2004 09:19:00, seen in SAN CAZIANO
i have to do in the onkeypress or in onchange the float (real) field
validation

I try something:

function ValidaCampo(nomeCampo,TotInteri,TotDecimali)
{
DecimalPos=NomeCampo.value.Indexof(',');
Lungh=TotInteri+TotDecimali+1; //sum the ineger + decimal +
decimal separator


if ((window.event.charcode==',') && (DecimalPos>-1))
//i think exist a decimal separator so i don't add any other
else
if (DecimalPos<>TotInteri+1)
//i haven' t insert too much integer
else
if i haven't add any decimal, i add a separator with two zero value
else
if nomecampo.length<>Lungh
//error

}

Feel free to post in both Italian and English (for short text); it would
be easier to understand.

See <URL:http://www.merlyn.demon.co.uk/js-valid.htm>.

Don't validate on keypress IMHO; do onChange or onSubmit.

If you are only doing arithmetic on the result, you have no need to
adjust its string format.

See FAQ via below.
 
S

SAN CAZIANO

hi, I see the code in that url you give me, but I am only at beginning of
javascript and php/html so it is very difficult to understand it for me, so
can you give me an example of code for validate a decmal floating number
with 5 number before the decimal separator and 2 number after it.

thanks a lot,
alberto
 
R

RobG

SAN said:
hi, I see the code in that url you give me, but I am only at beginning of
javascript and php/html so it is very difficult to understand it for me, so
can you give me an example of code for validate a decmal floating number
with 5 number before the decimal separator and 2 number after it.

From the link given by Dr. John (watch for wrapping) with
some extra comments:

// This just sets the value of S, you may get it
// some other way
S = F.X2.value

// See if there are from 1 to 4 digits at the start
// of the string S
OK = /^\d{1,4}(\.\d\d?)?$/.test(S)

// If the result of the above was true, then
// make sure there are exactly two digits
// after the decimal point
if(OK) S=S.replace(/(\.\d)$/,"$10").replace(/^(\d+)$/,
"$1.00")

To modify it for your purpose, you just need to change the
second line to:

OK = /^\d{5}(\.\d\d?)?$/.test(S)

So your number must have 5 digits, a decimal point, then
two digits. If you want the digital point to be ","
replace \.\ with \,\ .

Below is a small page that illustrates how to use it. Of
course, you will need to do validation and handle errors, I
am just showing how to use the code above.

Cheers, Rob

<html>
<head>
<title>Numbers</title>
<script type="text/javascript">
function formatNum(a) {
var S = a.value;
var OK = /^\d{1,5}(\.\d\d?)?$/.test(S);
if (OK) {
S = S.replace(/(\.\d)$/, "$10").replace(/^(\d+)$/, "$1.00")
} else {
alert("You must enter a number");
}
return S;
}
</script>
</head>
<body>
<form name="aForm" action="">
<input type="text" name="A1" cols="15">
<input type="button" value="Check the number"
onclick="
var num = formatNum(this.form.A1);
this.form.A1.value = num;
">
</form>
</body>
</html>
 
M

Michael Winter

[snip]
OK = /^\d{1,4}(\.\d\d?)?$/.test(S)

Personally, I prefer:

/^(0|[1-9]\d{0,3})(\.\d\d?)?$/

unless you want leading zeros, of course.

[snip]
<form name="aForm" action="">

As you don't reference the form by name, there's not much point including
that attribute.
<input type="text" name="A1" cols="15">
<input type="button" value="Check the number"
onclick="
var num = formatNum(this.form.A1);
this.form.A1.value = num;
">

You could save the form element reference. As an intrinsic event attribute
is an anonymous function, variables declared with var will be local just
as in other contexts.

[snip]

Mike
 
R

RobG

Michael Winter wrote:
[snip]
Personally, I prefer:

/^(0|[1-9]\d{0,3})(\.\d\d?)?$/

unless you want leading zeros, of course.

Dunno. The OP said "validate a decmal floating number with 5 number
before the decimal separator and 2 number after it". I'm not exactly
sure what s/he meant - exactly 5? Up to 5? Zero padded?

My intention was just to show some working code based on the page
referenced by Dr. J. as a bit of a leg-up.
As you don't reference the form by name, there's not much point
including that attribute.

Dang, 10 extraneous characters (counting the extra space...).

[snip]
You could save the form element reference. As an intrinsic event
attribute is an anonymous function, variables declared with var will be
local just as in other contexts.

Which translates (I think) into:

the onclick could be written more concisely as:

onclick="A1.value=formatNum(A1);">

And to preempt questions on why I pass the reference to the text box
and not its value, it's because I felt like it. To trim the code even
further, the value can be passed so that the onclick becomes:

onclick="A1.value=formatNum(A1.value);">

and the first few lines of the function become:

function formatNum(S) {
var OK = /^\d{1,5}(\.\d\d?)?$/.test(S);

Thereby saving the presumption that "a" is a reference to an object and
allows formatNum to work on any string passed to it, making it more
flexible.

Pedantic? Hmmm, but we luvz ya for it Mike! :)

I learn more from your responses to posts than text I've tried - please
don't stop!

Cheers, Rob.
 
M

Michael Winter

[snip]
Dunno. The OP said "validate a decmal floating number with 5 number
before the decimal separator and 2 number after it". I'm not exactly
sure what s/he meant - exactly 5? Up to 5? Zero padded?

Yeah. A well-written question always helps...

[snip]

[MW:]
Dang, 10 extraneous characters (counting the extra space...).

I didn't say it because of that. Just the pointlessness of including an
attribute that serves no purpose.
Which translates (I think) into:

the onclick could be written more concisely as:

onclick="A1.value=formatNum(A1);">

That isn't what I was referring to, but yes I am being too picky here. I
didn't realise it until after I sent the post. I could have cancelled it,
but I was tired and it didn't occur to me.

What I was trying to say was that just as you save the result of a
reference

function validateForm(form) {
var elems = form.elements;

elems['controlName'] ...
}

like that, the same could apply to the intrinsic event

onclick="var o = this.form.elements['A1']; o.value = formatNum(o);"

because the variable, o, would be local as the browser would translate
that to:

elemRef.onclick = function(event) {
var o = this.form.elements['A1'];
o.value = formatNum(o);
};
And to preempt questions on why I pass the reference to the text box
and not its value, it's because I felt like it.

It hadn't occurred to me, actually. :p As I said, I was tired. :)

[snip]
Pedantic?

I know. I know... :(
Hmmm, but we luvz ya for it Mike! :)

I doubt that, somehow.
I learn more from your responses to posts than text I've tried -
please don't stop!

I suppose that (learning) is the main thing.

Mike
 
R

Richard Cornford

RobG said:
Michael Winter wrote:

Which translates (I think) into:

the onclick could be written more concisely as:

onclick="A1.value=formatNum(A1);">

And to preempt questions on why I pass the reference to the
text box and not its value, it's because I felt like it. To
trim the code even further, the value can be passed so that
the onclick becomes:

onclick="A1.value=formatNum(A1.value);">
<snip>

If the intention here is to exchange the property accessor -
this.form.A1 - (better as this.form.elements.A1) for the identifier -
A1 -, then that is a risky practice as it requires that the reference to
the form element be available as a named property of an object on the
scope chain of the browser-constructed anonymous event handling
function.

As the global object is always on a function's scope chain all of the
browsers that make references to named form elements into named
properties of the global object will be able to pick up that reference.
Unfortunately, (or perhaps fortunately, as stuffing things into the
global namespace at the drop of a hat is not really a good idea) some
browsers just don't facilitate that (and more so with named elements
than IDed elements).

Some browsers do, however, generate a custom scope chain for their
attribute originating, internally generated event handling functions.
The process can be conceived as like wrapping the code provided for the
HTML attribute in a stack of - with - statements:-

onclick="A1.value=formatNum(A1);"

- becomes (like):-

function(e){
with(this){
with(this.form){
with(document){
A1.value=formatNum(A1);
}
}
}
}

Where the exact list of objects added to the scope chain varies
depending on the browser and the context of the element for which the
event handling method is created. The possibilities range form browsers
that provide no custom scope chain at all (Opera <= 6 being one
example), to browsers that will, in some contexts, pace every ancestor
of the element in the DOM on the scope chain (Mozilla/Gecko).

Unqualified - A1 - is resolved on the scope chain above as a named
property of the FORM element on the scope chain, *if* the browser has
paced the form on the scope chain. As it is known that some browsers do
not augment the scope chain of internally generated event-handling
functions at all, cross-browser scripting requires that code provided
for event handling attributes be written as if the only candidates for
the resolution of unqualified identifier on the scope chain were the
local "Variable" object (at the top of the chain, holding function local
variables and formal parameters ("event"?)), and the global object. Any
reliance on picking up, for example, a named form element as a named
property of the containing form using its name as an unqualified
identifier, will guarantee needless (avoidable) failure on some
browsers.

Incidentally, when I say that the scope chain augmentation is only like
wrapping the function body in a stack of - with - statements I am
observing an oddity of the behaviour of IE. If - with -, or any
mechanism that had a similar effect, was used, moving the event handler
to a different element would leave the scope chain used in the
resolution of identifiers unchanged. And this is indeed what happens on
Mozilla and Opera 7. On IE, if you move an internally generated event
handling function to a different element it gets a scope chain, when
executed, related to its new context of execution. The IE scope chains
are dynamic and created at the point of either assignment or execution.
(and calling one of these function directly as a function (instead of as
a method of an element) produces some very ECMAScript unlike behaviour
in identifier resolution). Of course moving internally generated event
handling functions is extremely unlikely to be something anyone want to
do (beyond experimenting with the subject).

Richard.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 14
Oct 2004 22:05:05, seen in RobG
To modify it for your purpose, you just need to change the
second line to:

OK = /^\d{5}(\.\d\d?)?$/.test(S)
^
Omit the first, since if there is a non-integer
part it should have two digits. Omit the second, and the parentheses,
if the non-integer part is mandatory (it was not so at first, but now it
seems to be so).

In the question, the word "number" should be "digit".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top