我应该如何修改PHP和Javascript文件,以使该复选框为必填项?

时间:2019-02-23 15:33:30

标签: javascript php forms validation

我希望表单的复选框为必填项,但是我不知道如何修改服务器端的PHP文件和JS文件。

我已经阅读了一些有关此问题的答案,但是由于我对PHP和Javascript的了解很少,因此我无法找到一种实现形式的方法。

我添加了一个简单的REQUIRED,但正如我所读的,这还不足以满足我的目的。

我向他们展示了我的HTML,PHP和JS文件,看它们是否给我关于什么的想法 我应该添加或修改它才能以正确的方式进行操作。

这些是表单具有的arcivos,如果我必须添加更多的arcivo,请毫不犹豫地告诉我我还应该向您显示什么。

谢谢

//  -************** FILE PHP ************  //

<?php

/***************** Configuration *****************/

$contact_email_to = "cuentaclientdiana@gmail.com";
$contact_subject_prefix = "Mensaje de formulario de contacto: ";
$contact_error_name = "¡El nombre es demasiado corto o vacío!";
$contact_error_email = "Por favor, introduzca un email valido";
$contact_error_subject = "El tema es demasiado corto o vacío!";
$contact_error_message = "Mensaje demasiado corto! Por favor, introduzca algo.";

/********** Do not edit from the below line ***********/

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  die('Sorry Request must be Ajax POST');
}

if(isset($_POST)) {

  $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
  $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
  $subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
  $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

  if(strlen($name)<4){
    die($contact_error_name);
  }

  if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    die($contact_error_email);
  }

  if(strlen($message)<3){
    die($contact_error_subject);
  }

  if(strlen($message)<3){
    die($contact_error_message);
  }

  if(!isset($contact_email_from)) {
    $contact_email_from = "contactform@" . @preg_replace('/^www\./','', $_SERVER['SERVER_NAME']);
  }

  $sendemail = mail($contact_email_to, $contact_subject_prefix . $subject, $message,
    "From:  $name <$contact_email_from>" . PHP_EOL .
    "Reply-To: $email" . PHP_EOL .
    "X-Mailer: PHP/" . phpversion()
  );

  if( $sendemail ) {
    echo 'OK';
  } else {
    echo 'No se pudo enviar el correo! Por favor, compruebe su configuración de correo PHP.';
  }
}
?>


// ***********  FILE   JAVASCRIPT ********* //


jQuery(document).ready(function($) {
"use strict";

    //Contact
    $('form.contactForm').submit(function(){

        var f = $(this).find('.form-group'), 
        ferror = false, 
        emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

        f.children('input').each(function(){ // run all inputs

            var i = $(this); // current input
            var rule = i.attr('data-rule');

            if( rule !== undefined ){
            var ierror=false; // error flag for current input
            var pos = rule.indexOf( ':', 0 );
            if( pos >= 0 ){
                var exp = rule.substr( pos+1, rule.length );
                rule = rule.substr(0, pos);
            }else{
                rule = rule.substr( pos+1, rule.length );
            }
            
            switch( rule ){
                case 'required':
                if( i.val()==='' ){ ferror=ierror=true; }
                break;
                
                case 'minlen':
                if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
                break;

                case 'email':
                if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
                break;

                case 'checked':
                if( !i.attr('checked') ){ ferror=ierror=true; }
                break;
                
                case 'regexp':
                exp = new RegExp(exp);
                if( !exp.test(i.val()) ){ ferror=ierror=true; }
                break;
            }
                i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
            }
        });
        f.children('textarea').each(function(){ // run all inputs

            var i = $(this); // current input
            var rule = i.attr('data-rule');

            if( rule !== undefined ){
            var ierror=false; // error flag for current input
            var pos = rule.indexOf( ':', 0 );
            if( pos >= 0 ){
                var exp = rule.substr( pos+1, rule.length );
                rule = rule.substr(0, pos);
            }else{
                rule = rule.substr( pos+1, rule.length );
            }
            
            switch( rule ){
                case 'required':
                if( i.val()==='' ){ ferror=ierror=true; }
                break;
                
                case 'minlen':
                if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
                break;
            }
                i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
            }
        });
        if( ferror ) return false; 
        else var str = $(this).serialize();		
            $.ajax({
                type: "POST",
                url: "contactform/contactform.php",
                data: str,
                success: function(msg){
                   // alert(msg);
                    if(msg == 'OK') {
                        $("#sendmessage").addClass("show");			
                        $("#errormessage").removeClass("show");	
                    }
                    else {
                        $("#sendmessage").removeClass("show");
                        $("#errormessage").addClass("show");
                        $('#errormessage').html(msg);
                    }
                    
                }
            });
        return false;
    });

});
<!DOCTYPE html>
<html lang="en">
<body>
<section id="contact-page">
    <div class="container">
      <div class="center">
        <h2>Deje su mensaje</h2>
        <p class="lead">Deje su mensaje con sus ideas y veremos que es lo mejor para usted y su negocio.</p>
      </div>
      <div class="row contact-wrap">
        <div class="col-sm-8 col-sm-offset-2">
          <div id="sendmessage">Your message has been sent. Thank you!</div>
          <div id="errormessage"></div>
          <form action="" method="post" role="form" class="contactForm">
            <div class="form-group">
              <input type="text" name="name" class="form-control" id="name"  placeholder="Nombre" data-rule="minlen:4" data-msg="Por favor ingrese al menos 4 caracteres" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <input type="email" class="form-control" name="email" id="email"   placeholder="Email" data-rule="email" data-msg="Por favor introduzca una dirección de correo electrónico válida" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <input type="text" class="form-control" name="subject" id="subject"  placeholder="Tema" data-rule="minlen:4" data-msg="Por favor ingrese al menos 8 caracteres del tema" />
              <div class="validation"></div>
            </div>
            <div class="form-group">
              <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Por favor escribe algo para nosotros" placeholder="Mensaje"></textarea>
              <div class="validation"></div>
            </div>
            <input type="checkbox" name="acceptPolicies" required="required" value="acceptPolicies" /> He leído y acepto su <a href="privacidad.html" target="_blank">Política de Privacidad</a>
            <div class="text-center"><button type="submit" class="btn btn-primary btn-lg">Enviar</button></div>
          </form>
        </div>
      </div>
      <!--/.row-->
    </div>
    <!--/.container-->
  </section>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

除非选中复选框输入,否则不会将任何内容发送到表单的端点。

因此,您可以在后端简单地添加以下代码:

if (!isset($_POST['acceptPolicies'])) {
  // Checkbox wasn't checked, handle appropriately (error message, log, redirection, etc.)
}

此外,作为一般建议,您应避免过多使用die(除非在重定向标头或此类特定出现之后)。如果表单存在输入错误,请在将错误密钥存储到会话中后重定向到表单,然后在表单上显示相应的错误消息。