1

I have a php form that gets validated through javascript. I would like to add another field to the form where the user has to confirm their email. How can I do this in the javascript validation file please? Here is my current validation for the initial email form:

this.setHandler('email',
        function (value) {
            regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
            return regex.test(value);
        }
    );
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
A Smith
  • 237
  • 5
  • 16

2 Answers2

1

Adapt something like this...

this.setHandler('email-confirm',
    function (value) {
        return value == document.getElementsByTagName('email')[0].value;
    }
);

Assuming your confirm email's name (or whatever the first argument to setHandler()) is email-confirm, and the original email input's name is email (and assuming it is the first element of such).

Basically, I'm comparing the current value of the email-confirm to the original value, and if they are equal, the function returns true.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Hi, thanks for your answer. Could you explain what the above code does so I get a better understanding please? – A Smith Feb 14 '12 at 22:58
0

Of course the real answer is be careful when writing a regex to validate email, as most people get it wrong. Yours ignores the first part for something like myname+other@domain.com as well as failing for custom top-level domains.

If you can, use an existing library like jquery-validate, because they have already done the hard work for you and have built-in email validation as well as field comparisons.

If you need to write it yourself, use a better expression.

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

Anyway, you actually asked on how to "confirm" their email...which isn't it just a matter of comparing one field against another.

// using jQuery
this.setHandler('email2',
    function (value) {
        return (value == $("#email").val());
    }
);
Community
  • 1
  • 1
cdm9002
  • 1,930
  • 1
  • 15
  • 15
  • Hi, thanks for your reply. What does the above code do then? When I say confirm, I mean to confirm that the user has typed in the right email address and not made a mistake. Surely all it would need to do for that would be to compare the original email field with the new confirm-email field? – A Smith Feb 14 '12 at 23:46