Validate form before sending

3

I have an HTML page with an e-mail submission form. I need to check on the same page whether the fields were filled out or not at the time the user clicks the Submit button. Apparently it is bypassing the javascript function and it is sending the email regardless of the content of the form.

Follow the script.js with the function and then index.html.

function checkForm() {
    // Fetching values from all input fields and storing them in variables.
    var nome = document.getElementById("nome").value;
    var email = document.getElementById("email1").value;
    var fone = document.getElementById("telefone").value;
    var mensagem = document.getElementById("mensagem").value;

    //Check input Fields Should not be blanks.
    if (nome == '' || email == '' || fone == '' || mensagem == '') {
        alert("Por favor preencha todos os campos.");
    } else {
        //Notifying error fields
        var name = document.getElementById("nome");
        var mail = document.getElementById("email");
        var telefone = document.getElementById("telefone");
        var mensagemp = document.getElementById("mensagem");
        //Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
        if (name.innerHTML == 'Nome' || mail.innerHTML == 'E-mail' || telefone.innerHTML == 'Telefone' || mensagemp.innerHTML == 'Sua Mensagem') {
            alert("Por favor, preencha o formulário com informações válidas");
        } else {
            //Submit Form When All values are valid.
            document.getElementById("myForm").submit();
        }
    }
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>

<form method="post" action="sendmail.php">
	<input type="text" class="text" value="Nome" name="nome" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Nome';}">
	<input type="text" class="text" value="E-mail" name="email" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'E-mail';}">
	<input type="text" class="text" value="Telefone" name="telefone" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Telefone';}">
	<textarea name="mensagem" required onfocus="if(this.value == 'Sua mensagem') this.value='';" onblur="if(this.value == '') this.value='Sua mensagem';" >Sua mensagem</textarea>
	<input type="submit" value="[ Enviar Mensagem ]" onclick="checkForm()" />
</form>

</body>
</html>

sendmail.php

<?php

  $to      = '[email protected]';
  $subject = 'Contato Site';
  $message = "Nome: ".$_POST['nome']."\r\nE-mail: ".$_POST['email']."\r\nTelefone: ".$_POST['telefone']."\r\n\r\nMensagem:\r\n".$_POST['mensagem']."\r\n\r\n";
  $headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
  mail($to, $subject, $message, $headers);

header("Location: http://www.site.com.br/obrigado.html");

die();
?>
    
asked by anonymous 17.07.2017 / 18:56

4 answers

2

Response + justification

First, I'd like to mention that you're using a somewhat obsolete way of doing what you need, because you can use the placeholder attribute of html5 instead of doing all that part of onBlur and onFocus , and you also do not need to take element by element to validate, you can add a class in common to all of them and pick an array with all the elements and go through them with a loop of validating one by one, so it's much simpler.

Example

See how your code got extremely low on this example I created for you on jsFiddle

    
17.07.2017 / 19:35
3

The fields on your form and the form itself do not have the id attribute, required to use .getDocumentById ("alguid"). Your function should also return false if validation error occurs ... Try as below:

Form

<form method="post" action="sendmail.php" id="myForm">
    <input type="text" class="text" value="Nome" id="nome" name="nome" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}">
    <input type="text" class="text" value="E-mail" id="email" name="email" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}">
    <input type="text" class="text" value="Telefone" id="telefone" name="telefone" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}">
    <textarea name="mensagem" id="mensagem" required onfocus="if(this.value == '') this.value='';" onblur="if(this.value == '') this.value='';" >Sua mensagem</textarea>
    <input type="submit" value="[ Enviar Mensagem ]" onclick="return checkForm()" />
</form>  

JS

<script>
    function checkForm() {
        // Fetching values from all input fields and storing them in variables.
        var nome = document.getElementById("nome").value;
        var email = document.getElementById("email").value;
        var fone = document.getElementById("telefone").value;
        var mensagem = document.getElementById("mensagem").value;

        //Check input Fields Should not be blanks.
        if (nome == '' || email == '' || fone == '' || mensagem == '') {
            alert("Por favor preencha todos os campos.");
            return false;
        } else {
            //Notifying error fields
            var name = document.getElementById("nome");
            var mail = document.getElementById("email");
            var telefone = document.getElementById("telefone");
            var mensagemp = document.getElementById("mensagem");
            //Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
            if (name.innerHTML == 'Nome' || mail.innerHTML == 'E-mail' || telefone.innerHTML == 'Telefone' || mensagemp.innerHTML == 'Sua Mensagem') {
                alert("Por favor, preencha o formul&aacute;rio com informa&ccedil;&otilde;es v&aacute;lidas");
                return false;
            } else {
                //Submit Form When All values are valid.
                document.getElementById("myForm").submit();
                return true;
            }

        }
    }
</script>
    
17.07.2017 / 19:13
2

Because you are calling getElementById , but if you check neither field has the id attribute. Example:

<input type="text" class="text" value="Nome" id="nome" name="nome" required onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Nome';}">

You have to put ids in the fields to use this DOM method.

The button is of type submit and comes first before the onclick function ie this action will be executed before checkform , causing a conflict. Leave the type as button . Example:

<input type="button" value="[ Enviar Mensagem ]" onclick="checkForm()" />
</form>
    
17.07.2017 / 19:04
0

HTML5 has brought several possibilities and especially facilities for developers. One of these is related to form validation. What used to be done with some time and JavaScript, today can be done directly in HTML and in a much shorter time.

HTML5 includes a fairly robust form validation mechanism based on input tag attributes: type, pattern, and require. Thanks to these new attributes, you can delegate some data verification functions to the browser.

<form method="post" action="words.php">
    <input type="text" class="text required" value="" placeholder="nome" name="nome" required="required">
    <input type="email" class="text required" value="" placeholder="email" name="email" required="required" >
    <input pattern="[0-9]{2}[\s][0-9]{4}-[0-9]{4,5}" type="tel" class="text required" value="" placeholder="dd dddd-dddd ou dd dddd-ddddd" name="telefone" required="required">
    <textarea class="required" placeholder="mensagem" name="mensagem" id="mensagem" required="required"></textarea>
    <input type="submit" value="[ Enviar Mensagem ]" />
</form>
  • input type="text" for simple text data manipulation
  • input type="email" validates the field to ensure that the entered data is in fact a valid email address.
  • input type="tel" to validate phones that together with the pattern attribute accepts a regular expression, and we will see below.
  • The pattern attribute of the input tag is responsible for validating what is being typed, and the pattern must always be defined through a regular expression.
  • pattern="[0-9]{2}[\s][0-9]{4}-[0-9]{4,5}" indicates 2 digitos espaço 4 digitos tracinho 4 ou 5 digitos (validates DDD and 8-digit fixed-line phones and DDD and 8- or 9-digit cell phones.)

The required attribute is a Boolean attribute used to indicate that a determining form field is required to send the form field. When you add this attribute to a form field, the browser forces the user to enter data in that field before submitting the form.

    
17.07.2017 / 19:10