-1

I know this question will be closed because I studied many example of this but please see I think I am doing something different.

I coded my server side PHP email validation with this:

if (!filter_var($user_new_email, FILTER_VALIDATE_EMAIL)) {
        $errors .="Email,"; 
        $pass    = false;
             }

My client side email validation is:

function validateEmail(txtEmail){
 var a = document.getElementById(txtEmail).value;
 var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
   if(filter.test(a)){
    return true;
   }
   else{
    return false;
   }

So in my client side if I enter only username@domain (without .com), it's valid. I don't want that.

I need the same validaton in both client and serverside. How to update my regular expression in JavaScript?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Shreya Ghoshal
  • 79
  • 2
  • 14

3 Answers3

3

Just escape the last '.' (dot) in your regex. When not escaped or inside brackets, a dot matches any character except new line. So the correct value for filter is:

var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+\.[a-z]{1,4}$/;
Diego
  • 18,035
  • 5
  • 62
  • 66
1

@Diego has the answer you're looking for, but there are a few reasons why it really doesn't matter if you validate completely in your javascript:

  1. Client-side validation can always be bypassed. You have to do the complete validation on the server side, so client-side validation is primarily a courtesy to your regular users. At most, it serves to provide fast feedback regarding form errors and saves you a few requests.
  2. Validating email addresses is hard. The majority of validators (including your JavaScript example) are too strict, according to RFCs 2822 and 5322. Read this article to get some idea of how bizarre valid addresses can be.
bonsaiviking
  • 5,825
  • 1
  • 20
  • 35
0

use jquery validation plugin it is very easy to use and customizable eg.Jquery Validation Plugin and Position Absolute Jquery validation plugin

Amritpal Singh
  • 1,765
  • 1
  • 13
  • 20