Using two Onsubmit in Javascript and If Function within an Alert

Asked

Viewed 2,691 times

2

I’m training JavaScript with HTML and CSS and I’m creating a simple web page where I’ll do the BMI calculation. My user besides informing his weight and height,should inform his data:name,e-mail,..

Through the JavaScript I must perform the IMC calculations and validate both the user’s name and e-mail, I have an example that I am following, but have a command that I am not understanding right : ONSUBMIT

  <section class="userinfo">
      <form class="info" action="index.html" method="post" onsubmit="return validateName()">
        <ul>
          <li><label for="nome">Nome:</label>
              <input type="text" name="nome" placeholder="Digite seu nome" id="name" required/></li>
          <li><label for="email">E-mail:</label>
              <input type="email" name="email" placeholder="Digite seu E-mail" id="email" required></li>
          <li><label for="telefone">Telefone:</label>
              <input type="tel" name="telefone" placeholder="(xx)xxxxx-xxxx" id="telefone"/></li>

In the field of Form I wouldn’t have to inform two onsubmit ? One validateName and another validateEmail?

My second question is about the functioning of JavaScript

function validateName(){
  var name = document.getElementById('name').value;
  var nameValidator = /^[a-záàâãéèêíïóôõöüúçñ' ]{5,}$/i;

  if (!nameValidator.test(name)){
    alert("Nome invalido")
    return false}
}

That one !if means the logical operator não correct? My doubt is actually in condition

nameValidator.test(name)

That one namevalidator, would not have to be called : validateName ,which is my function for validation of my user name?

2 answers

4


"In the Form field I wouldn’t have to report two onsubmit ? One validateName and another validateEmail?"

In the form, the event onsubmit is an event that happens when you try to "submit" the form, that is, for example when you click a button submit. Then you can run one or more functions, can do all the validations you want.
Finally, you can return true or false according to your validations for whether or not to proceed with Submit. See the example:

<form class="info" action="index.html" method="post" onsubmit="return validateForm()">

function validateForm() {
   var ok = validateName();
   if (ok) {
      ok = validateEmail();
   }

   return true;
} 

In that case, the Function "validateForm" executes the two validations you mentioned, each of which must return true or false.
In the code use the if (ok) to check if the first validation has returned true to make the second. If the first has already returned false nor executes the second.
But you may prefer to run the second to display some message, it’s just a way to simplify as suggestion.

"This ! if means the correct logical operator?"
Exactly, it means "if not".

"This namevalidator wouldn’t have to be called : validateName ,which is my function for validating my user name?"
In that case nameValidator is a variable that contains a Regular Expression, something that will validate the format of the name, which does not need to have the same name as the Function

More about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

EDIT: here a suggestion to unify validation and a single method:

function validateForm(){
  // primeiro o nome:
  var name = document.getElementById('name').value;
  var nameValidator = /^[a-záàâãéèêíïóôõöüúçñ' ]{5,}$/i;

  if (!nameValidator.test(name)){
    alert("Nome inválido");
    return false;
  }

  // Depois email:
  var emmail = document.getElementById('email').value;
  var emailValidator = /\S+@\S+\.\S+/;

  if (!emailValidator.test(email)){
    alert("Email inválido");
    return false;
  }

  return true;
}
  • So I have to have two onsubmits anyway correct? because having only the one of the name,?

  • and one more question,Function validateForm() { var ok = validateName(); if (ok) { ok = validateEmail(); } Return ok; Inside that if I’m validating both fields? or just email? Because I didn’t quite understand why the variable name is out of the if and the variable email is in!

  • @Carolm, in the role validateName() is already validating in the name as in your example, just need to create the function code validateEmail(). I put so to answer exactly as you asked, but to simplify you can make the two validations within the function validateForm, I think it gets easier and clear

  • I put an example in the answer to the idea of validating everything in one Function

  • now it’s even easier to understand! Thank you so much for helping Ricardo!

1

The event onSubmit Javascript is a great way to automate tasks. With it, you can make the browser validate the information that was sent through a form before the server receives it.

the event onSubmit executes a series of commands (or only one) at the moment the visitor of a site clicks on the send button of a form.

Example

Note: I removed the required and I emailed type text to facilitate verification

function validat(){
var name = document.getElementById('name').value;
var nameValidator = /^[a-záàâãéèêíïóôõöüúçñ' ]{5,}$/i;

   if (!nameValidator.test(name)){
     console.log("Nome invalido")
     return false
   }
        
var stremail= document.getElementById('email').value;

   if( stremail=="" || stremail.indexOf('@')==-1 || stremail.indexOf('.')==-1 ){
     console.log( "Por favor, informe um E-MAIL válido!" );
     return false;
   }
}

 
<form class="info" action="/questions?sort=newest" method="post" onsubmit="return validat()">
<ul>
    <li><label for="nome">Nome:</label>
        <input type="text" name="nome" placeholder="Digite seu nome" id="name"/></li>
    <li><label for="email">E-mail:</label>
        <input type="text" name="email" placeholder="Digite seu E-mail" id="email"></li>
</ul>
<input type="submit" value="Validar">
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.