0

Hello I am doing form validations from javascript. I managed to do it but I want my code to be reusable for various forms. My idea is to put the name of the form as a parameter of the jS function but it is not working. Can anybody help me?

<form action="<?= FRONT_ROOT?>/user/edit" method="POST" name="editForm" onsubmit="return(validator());">

 function validator() {
         var emailID = document.editForm.email.value;
         atpos = emailID.indexOf("@");
         dotpos = emailID.lastIndexOf(".");
         
         if (atpos < 1 || ( dotpos - atpos < 2 )) {
            alert("Please enter a valid email address.")
            document.editForm.email.focus() ;
            return false;
         }

         if( document.editForm.password.value.length < 8 ) {
            
            alert( "The password must have at least 8 characters." );
            document.editForm.password.focus() ;
            return false;
         }
         
         return( true );
}

My idea is to do something like this but it doesn't work

<form action="<?= FRONT_ROOT?>/user/edit" method="POST" name="editForm" onsubmit="return(validator(this.name));">

 function validator(genericForm) {
         var emailID = document.genericForm.email.value;
         atpos = emailID.indexOf("@");
         dotpos = emailID.lastIndexOf(".");
         
         if (atpos < 1 || ( dotpos - atpos < 2 )) {
            alert("Please enter a valid email address.")
            document.genericForm.email.focus() ;
            return false;
         }

         if( document.genericForm.password.value.length < 8 ) {
            
            alert( "The password must have at least 8 characters." );
            document.genericForm.password.focus() ;
            return false;
         }
         
         return( true );
}
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • Have you looked at any jQuery form validation plugins? The question was ambiguous because you want to make it reusable but other patterns / libraries already exist – hppycoder Mar 16 '21 at 19:13
  • Do you need to do this at all? Set the right attributes on your `` and the browser will do it for you. Try `type="email"` and `minlength="8"`, for starters. – Tangentially Perpendicular Mar 16 '21 at 19:19
  • Yeah but i need do it like that. Without plugins. – Franco Ferreyra Mar 16 '21 at 21:21
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – CBroe Mar 17 '21 at 09:21

0 Answers0