2016-10-15 5 views
2

私は次のフォームの検証をしています。エラーがなければ警告を行うPHPフォームのバリデーション

<?php 

    $error_occured = 0; 
    $error_name = ""; 
    $error_email = ""; 
    $error_contact = ""; 
    $error_comments = ""; 

    if(isset($_POST["tx_name"])) { 

      if(($tx_name == "") || (!preg_match("/^[a-zA-Z ]*$/",$tx_name))) { 
        $error_occured = 1; 
        $error_name = "Please enter a valid name"; 
       } 

      if(($tx_email == "") || (!filter_var($tx_email, FILTER_VALIDATE_EMAIL))) { 
        $error_occured = 1; 
        $error_email = "Please enter a valid email"; 
       } 

      if(($tx_contact == "") || !(is_numeric($tx_contact))) { 
        $error_occured = 1; 
        $error_contact = "Please enter a valid contact number"; 
       } 

      if($tx_comments == "") { 
        $error_occured = 1; 
        $error_comments = "Please enter your message"; 
       } 


     } 

    if(isset($_POST["tx_name"]) && $error_occured = 0) { 
      echo "<script>alert('Hi!');</script>"; 
     } 

?> 

検証は正常に動作し、エラーがなければ警告を発することになっています。しかし、エラーなしでフォームを送信すると、警告メッセージは表示されません。これをどうやって解決するのですか?

+1

のように試してみてください。ブール値を使用することも悪い考えではありません。 –

+0

Yash Mehtaありがとう、私は今それを理解しています。 – gosi123

答えて

1

は `$ error_occured == 0 'を使用し、最後の条件でこの

<?php 

$error_occured = 0; 
$error_name = ""; 
$error_email = ""; 
$error_contact = ""; 
$error_comments = ""; 

if(isset($_POST["tx_name"])) { 

     if(($tx_name == "") || (!preg_match("/^[a-zA-Z ]*$/",$tx_name))) { 
       $error_occured = 1; 
       $error_name = "Please enter a valid name"; 
      } 

     if(($tx_email == "") || (!filter_var($tx_email, FILTER_VALIDATE_EMAIL))) { 
       $error_occured = 1; 
       $error_email = "Please enter a valid email"; 
      } 

     if(($tx_contact == "") || !(is_numeric($tx_contact))) { 
       $error_occured = 1; 
       $error_contact = "Please enter a valid contact number"; 
      } 

     if($tx_comments == "") { 
       $error_occured = 1; 
       $error_comments = "Please enter your message"; 
      } 

    if($error_occured != 1) { 
     echo "<script>alert('Hi!');</script>"; 
     } 
} 



?> 
+0

これは動作します、ありがとう!しかし、私は質問があります、なぜ '($ error_occured!= 1)'の代わりに 'if($ error_occured = 0)'を置くとうまくいかないのですか? – gosi123

+2

'=='が必要です。それは、あなたが等しいかどうかをチェックする方法です。私の例では、あなたが1/0を持っているので、違うかどうかをチェックします。 2、3、8などのエラーがさらにある場合は、 '=='の方が良いでしょう。 –

+1

ありがとう、私は今理解しています。 – gosi123

関連する問題