Email form validation with javascript

Asked

Viewed 784 times

-1

I created a form to send email, I can send the email but I can’t check if the fields are filled.

 
<script type="text/javascript">
function checkEmail () {
	var name = document.form.name;
	var email = document.form.email;
	var subject = document.form.subject;
	var message = document.form.message;
	var count = 0;
	var flagError = false;
	var error="";
	
	if (name == "") {
		error += "O campo Nome deve ser preenchido.";
		count = count + 1
		flagError = true;
	}
	
	if (email == "") {
		error += "O endereço de e-mail deve ser preenchido.";
		count = count + 1
		flagError = true;
	}
	
	if (subject == "") {
		error += "O campo Assunto deve ser preenchido.";
		count = count + 1
		flagError = true;
	}
	
	if (message == "") {
		error += "O campo Mensagem deve ser preenchido.";
		count = count + 1
		flagError = true;
	}
	
	if (count > 0 )
          alert("Os seguintes erros foram encontrados:\n" + erro);
	
	if (!flagError) {
		var illegalChars = /(@.*@)|(@\.)|(@\-)|(@_)(\.@)|(\-@)|(\.\.)|(^\.)|(\.$)|(\.\-)|(\._)|(\-\.)|(_\.)|(^_)|(_$)|(_\-)|(\-\-)|(^\-)|(\-$)|(\-_)/;
		if (email.match(illegalChars)) {
			error += "O endereço de e-mail contém caracteres inválidos.";
			count = count + 1
			flagError = true;
		}
	}

	if (!flagError) {
		var emailFilter = /^\S+\@(\[?)[a-zA-Z0-9_\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!(emailFilter.test(email))) { 
			error += "O endereço de e-mail não está em um formato válido.";
			count = count + 1
			flagError = true;
		}
	}

	if (!flagError) {
		var emailFilter = /^([a-zA-Z0-9\@_\-\.\+]+)$/;
		if (!(emailFilter.test(email))) { 
			error += "O endereço de e-mail não está em um formato válido.";
			count = count + 1
			flagError = true;
		}
	}
	if (!flagError) {
		flagError = false;
		window.alert("Mensagem enviada com sucesso!")
		}

	if (flagError) {
		window.alert(error);
	}

	return !flagError;
}
</script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contato</title>
</head>

<body>

<p>Envie sua mensagem:</p>
    
    
<form method="post" action="http://www18.locaweb.com.br/scripts/FormMail.pl"/>


    
      <p><input type="text" placeholder="Nome" required name="name" id="name"></p>
      <p><input type="text" placeholder="Email" required name="email" id="email"></p>
      <p><input type="text" placeholder="Assunto" required name="subject" id="subject"></p>
      <p><input type="text" placeholder="Mensagem" required name="message" id="message"></p>
      <p>
        <button type="submit" name="Submit" onclick="javascript: var submit = checkEmail(getElementById('id').value); return submit;"> ENVIAR MENSAGEM </button>
      </p>
    </form>
    
    
    
</body>
</html>

  • What do you mean "does not check the fields"?

  • Does not check if the fields have been filled and does not check if the email is correct, and when all is right, does not appear the final email message sent successfully.

  • M. Nunes, managed to solve?

  • Yes, I managed to solve, I followed the guidance of Icaro Martins, it worked perfectly.

2 answers

1

I looked at your code I changed the way you’re trying to do the submit and fixed some problems and put some comments to explain what I did, I hope it helps you. = D

function checkEmail () {
        var frm = document.forms[0];
///                           ^ faltava o `s`, alem de ser uma array   
    	var name = frm.name.value;
///                     ^ name == `HTMLElement` pelo codigo parece que você quer o `value`
    	var email = frm.email.value;
    	var subject = frm.subject.value;
    	var message = frm.message.value;
    	var count = 0;
    	var flagError = false;
    	var error="";
    	
    	if (name == "") {
    		error += "O campo Nome deve ser preenchido.";
    		count = count + 1
    		flagError = true;
    	}
    	
    	if (email == "") {
    		error += "O endereço de e-mail deve ser preenchido.";
    		count = count + 1
    		flagError = true;
    	}
    	
    	if (subject == "") {
    		error += "O campo Assunto deve ser preenchido.";
    		count = count + 1
    		flagError = true;
    	}
    	
    	if (message == "") {
    		error += "O campo Mensagem deve ser preenchido.";
    		count = count + 1
    		flagError = true;
    	}
    	
    	if (count > 0 ){
              alert("Os seguintes erros foram encontrados:\n" + error);
///              a variável usada esta com o nome errado `erro`   ^
              return;
///             ^  estava aparecendo dois alerts entao coloquei um return aqui
        
    	}

    	if (!flagError) {
    		var illegalChars = /(@.*@)|(@\.)|(@\-)|(@_)(\.@)|(\-@)|(\.\.)|(^\.)|(\.$)|(\.\-)|(\._)|(\-\.)|(_\.)|(^_)|(_$)|(_\-)|(\-\-)|(^\-)|(\-$)|(\-_)/;
    		if (email.match(illegalChars)) {
    			error += "O endereço de e-mail contém caracteres inválidos.";
    			count = count + 1
    			flagError = true;
    		}
    	}

    	if (!flagError) {
    		var emailFilter = /^\S+\@(\[?)[a-zA-Z0-9_\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    		if (!(emailFilter.test(email))) { 
    			error += "O endereço de e-mail não está em um formato válido.";
    			count = count + 1
    			flagError = true;
    		}
    	}

    	if (!flagError) {
    		var emailFilter = /^([a-zA-Z0-9\@_\-\.\+]+)$/;
    		if (!(emailFilter.test(email))) { 
    			error += "O endereço de e-mail não está em um formato válido.";
    			count = count + 1
    			flagError = true;
    		}
    	}
    	if (!flagError) {
    		flagError = false;
            frm.submit()
///              ^ fazer o submit do form se tudo estiver correto 
    		window.alert("Mensagem enviada com sucesso!")
    		}

    	if (flagError) {
    		window.alert(error);
    	}

    	return !flagError;
    }
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Contato</title>
    </head>

    <body>

    <p>Envie sua mensagem:</p>
        
        
    <form method="post" action="http://www18.locaweb.com.br/scripts/FormMail.pl"/>


        
          <p><input type="text" placeholder="Nome" required name="name" id="name"></p>
          <p><input type="text" placeholder="Email" required name="email" id="email"></p>
          <p><input type="text" placeholder="Assunto" required name="subject" id="subject"></p>
          <p><input type="text" placeholder="Mensagem" required name="message" id="message"></p>
          <p>
            <button type="button" onclick="checkEmail()"> ENVIAR MENSAGEM </button>
          </p>
        </form>
        
        
        
    </body>
    </html>

  • Perfect, fully functional.

  • 1

    I appreciate the help

1

Analyzing your code, I found two problems that are preventing the functioning of your code.

  1. How you capture the value of the elements included in your formulário.
  2. The variable erro in the stretch: alert("Os seguintes erros foram encontrados:\n" + erro); there is no.

Solution¹: The estate form in the stretch document.form does not exist, I believe you tried to access the HTMLCollection by property forms. Note that the property forms returns a Collection of objects HTML according to the number of forms included in your source code, then to solve your problem you will access the attribute as follows: document.forms[índice], as there is only one form, we will use the index 0(since there is only one form). When accessing the form, the fields are also returned in a list of inputs. As you have 4 fields, we will access them as follows: document.forms[índice].[índice_do_elemento];. Note the following image to facilitate understanding.

inserir a descrição da imagem aqui

That is, to access the items, you will replace your code:

var name = document.form.name;
var email = document.form.email;
var subject = document.form.subject;
var message = document.form.message;

for:

var name = document.forms[0][0].value; //name
var email = document.forms[0][1].value; //email
var subject = document.forms[0][2].value; //subject
var message = document.forms[0][3].value; //message

Solution²: Just change the variable erro, for error. Once the variable erro there is no.

Note: There are various ways to access your form elements, the way I used to solve your problem was just to keep your syntax.

Browser other questions tagged

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