Validate form before sending

Asked

Viewed 14,424 times

4

I have an HTML page with an email submission form. I need to check on the same page if the fields were filled in or not at the moment the user clicks the Submit button. Apparently he is ignoring the javascript function and is sending the email regardless of the form content.

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

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();
?>
  • substitute type="submit" for type="button", this way will probably work its validation.

  • @Robertofagundes but so the form will not be submitted. Hearthz, what do you mean by "ignoring"? The alert defined in function are not displayed? In fact, use value to validate the value of a field, no innerHTML.

  • @Andersoncarloswoss will yes, he’s forcing the submit within the validation function.

  • @Robertofagundes in fact, I had not noticed it. My mistake.

  • And I guess I just had to define the attributes id fields. In JS you select the elements by id, but HTML does not specify them.

  • As already said, the fields are without ID, but try to validate the backend, in this case, your PHP code, if a user disables javascript he can skip the validation

Show 1 more comment

4 answers

3

The fields of your form and the form itself do not have the id attribute, required to use . getDocumentById("algumid"). Your function should also return false if there is an error in the validation... 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>
  • Even adding the necessary id’s and the Returns continues apparently bypassing and sending email anyway.

  • Compare the above code with your... If you run the above example will work... Don’t forget to leave the fields empty to validate.

  • Ah, and note the onblur="if (this.value == '') {this.value = 'Name';}" of your fields... so the fields will never be filled in to validate... : P

  • then... actually it would never be empty so in JS there is another check with the values you showed there: if (name.innerHTML == 'Name' || mail.innerHTML == 'E-mail' || phone.innerHTML == 'Phone' || messaging.innerHTML == 'Your Message')

2

For you are calling getElementById, but if you check none of the fields have the attribute id. 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 the ids in the fields to use this DOM method.

The button is with the guy submit and coming before the function onclick or this action will be performed before the checkform, causing a conflict. Let the type as button. Example:

<input type="button" value="[ Enviar Mensagem ]" onclick="checkForm()" />
</form>
  • So my dear, I really forgot about that "detail". But even after adding the proper id’s in the fields it keeps ignoring and sending the email with the empty or filled fields.

  • @Heathz changes the button type to button

  • with type button he did absolutely nothing.

2


Answer + justification

First, I would like to mention that you are using a somewhat obsolete way of doing what you need, because you can use the attribute placeholderHTML5 instead of doing all this part of onBlur and onFocus, and also you don’t need to take element by element to validate, you can add a common class to all of them and take an array with all the elements and go through them with a repeat loop validating one by one, so it gets much simpler.

Example

See how your code has gotten extremely smaller in this example I created for you:

function check_form(){
    var inputs = document.getElementsByClassName('required');
  var len = inputs.length;
  var valid = true;
  for(var i=0; i < len; i++){
     if (!inputs[i].value){ valid = false; }
  }
  if (!valid){
    alert('Por favor preencha todos os campos.');
    return false;
  } else { return true; }
}
<form method="post" action="sendmail.php" onsubmit="return check_form()" >
    <input type="text" class="text required" value="" placeholder="nome" name="nome">
    <input type="text" class="text required" value="" placeholder="email" name="email">
    <input type="text" class="text required" value="" placeholder="telefone" name="telefone">
    <textarea class="required" placeholder="mensagem" name="mensagem"></textarea>
    <input type="submit" value="[ Enviar Mensagem ]" />
</form>

See the code working on Jsfiddle.

  • 2

    opa! worked out my dear. I had completely forgotten about the placeholder... and look who had already used it on other occasions. About defining a common class and using it in an array, I hadn’t thought anything close to that haha. Thanks!

  • 1

    Sometimes you forget simple things that end up being really important. it is always good to update with the answers of the people here, and the question of the classes is only logic of programming even, with the time you will acquire greater experience begin to think directly on the easiest solution :P (or by laziness same, also serves)

0

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

HTML5 includes a pretty solid mechanism in form validation based on the input tag attributes: type, Pattern and require. Thanks to these new attributes, you can delegate some data check 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 accept a regular expression, and which we will see below.
  • The attribute pattern of the input tag is responsible for validating what is being typed and the default should always be set 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 landlines with DDD and 8 digits and cell phones with DDD and 8 or 9 digits.)

The attribute required is a Boolean attribute used to indicate that a determining form field is mandatory for sending the form. When adding this attribute to a form field, the browser forces the user to enter data in that field before submitting the form.

  • Does it have how to put two correct answers? hahaha

  • Actually the condition is correct in the question and you ended up reversing. Note that it sends the alert under these conditions, so if at least one field is not filled in, it displays the message. If you use the &&, the message will only be displayed if ALL fields are not filled in.

  • True! The thing is to add! P

Browser other questions tagged

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