The other day, a fellow wrote in to one of the PDF discussion forums to ask a question
about formatting user input in a PDF form. It was a fairly typical question. It went
Here is my problem: I am creating a form and in one field where the user enters a
validation number I want the field to automatically insert thedashes between the numbers,
for example: if a user inserts his numbers as 555555555 without dashes the custom Java
script would automatically insertthe dashes like this 5-55-55-5555. So what I am asking is
if someone could give me an example of the custom Java script that can do this.
It turns out there are many ways to solve the problem. First let’s just limit our
discussion to answering the question algorithmically. In other words, let’s just answer the
logic of the question at hand, and not worry about the messy details of trying to
idiot-proof things to the point where the user can’t screw things up beyond belief despite
our best efforts. Idiot-proofing forms is an important consideration, but for the moment,
let’s sidestep it.
The slice() function
on index positions that you supply as arguments. It is much easier to show how it
works than to describe in words how it works, so:
/// str = '555555555'; nine fives
/// we want to end up with 5-55-55-5555
formattedStr = str.slice(0,1) + '-' + 'str.slice(1,3) + '-' +
'str.slice(3,5) + '-' +
This may not be the only or best way; it’s just one way.
As for idiot-proofing: that’s a whole book. My approach would be to strip all the
non-numeric user input out of this particular string before beginning to format it. I.e.,
reduce it to a known state of just plain numbers run together. Then start putting dashes
(hyphens) in, where you want them.
The real way to attack formatting of user input is, of course, to make heavy use of
(O’Reilly) and also Jeffrey Friedl’s very fine MASTERING REGULAR EXPRESSIONS book
(also by O’Reilly) if syou are serious about learning to use regexes. In the meantime, open
suite) with a text editor and study the many examples of RegExp method usage in that file.
You’ll get some good ideas there of how things work.