0

Below is my javascript function which is already working...

but when i try to implement regular expression to check email is proper or not then my function does not work and does not display any message...

so plz suggest me how to implement this.

<script language="javascript">
 function validateFields(){
   var error = '0';
   var emailpattern =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/;

   if(document.getElementById('InvitationEmailAddress').value==""){
     document.getElementById('email_address_error').innerHTML = "Email address is required";
     error = '1';
   }

  if(document.getElementById('InvitationEmailAddress').value!="")
  {
    if(!InvitationEmailAddress.value.match(emailpattern)){  
     document.getElementById('email_address_error').innerHTML = "Email address is not valid";
     error = '1';
   }else{
     document.getElementById('email_address_error').innerHTML = "";
   }
 }


   if(document.getElementById('InvitationMessage').value==""){
     document.getElementById('message_error').innerHTML = "Welcome message is required";
     error = '1';
   }else{
     document.getElementById('message_error').innerHTML = "";
   } 
  if(error == 1){
     return false;
   }else{
     return true;
   }
 }
</script>
  • The only reliable way to check email addresses, other than rudimentary checks for a `@` or a `.` in the domain, is to send a mail there and see if it bounces. For instance, your regexp will fail on the new TLD of `.london`. –  Mar 03 '16 at 06:32

2 Answers2

0
if(!InvitationEmailAddress.value.match(emailpattern)){

Should be:

if(!document.getElementById("InvitationEmailAddress").value.match(emailpattern)){
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
  • but this is not validating when i insert multiple email like below example.....so what should change in regular expression...... for ex - - person1@example.com, person2@example.com – lucky smarty Mar 03 '16 at 06:10
  • Yes, he should call `document.getElementById`, but actually the way he wrote it should not fail, because elements are available on the windows object under their IDs. –  Mar 03 '16 at 06:31
-1

email regex = /^\w+([.-]?\w+)@\w+([.-]?\w+)(.\w{2,3})+$/

Also You are parsing the DOM everytime to search: InvitationEmailAddress element

you can save it in variable & can use this variable.

var inMsgEmRef = document.getElementById('InvitationEmailAddress');
Rajan Singh
  • 611
  • 4
  • 9