javascript,PHP - 如果输入字段不为空,则需要字段

时间:2016-07-04 09:30:28

标签: javascript php

如果input id='pass2' required value.lenght!= null,我想input id='pass1

<form action="perfil.php" method="post">
<table  width="100%" border="0">
<tr>
<td width="10" height="10"></td>
<td colspan=2><p align=justify></p></td>
<td width="4"></td>
</tr>
<tr>
<td width="10" height="10"></td>
    <td align="left"><font color=#ff0000 id="atencao" size="2em"></font></td>
     <td width="4"></td>
    </tr>
    <tr>
     <td></td>
  <td align="left">Password:</td>
  <td align="left"><input AUTOCOMPLETE=OFF type=password value="" id="password" name="password" style="WIDTH:140px;" maxlength="254" required></td>   
  </tr>
    <tr>
  <td></td>
  <td align="left">New Password :</td>
  <td align="left"><input AUTOCOMPLETE=OFF type=password value="" id="pass1" name="pass1" style="WIDTH:140px;" maxlength="254"></td>
   <td></td>
   </tr>
   <tr>
   <td></td>
   <td align="left">
    Confirm Password :</td>

 <td align="left"><input AUTOCOMPLETE=OFF type="password" value="" id="pass2" name="pass2" style="WIDTH:140px;" maxlength="254" onkeyup="checkPass(); return false;"></td>
  <span id="confirmarMessagem"></span>
<td></td>

如果pass2 value.lenght在提交时不为null或者字段开始获取输入时我想要pass1!= null。

2 个答案:

答案 0 :(得分:0)

我不会依赖jQuery来进行验证。我将在PHP中执行此操作。我还会将提交按钮命名为“ChangePassword&#39;。

    $sError = '';
    $sPass1 = '';
    $sPass2 = '';

    if(isset($_POST['ChangePassword'])){

        // if password is set and isnt blank string
        if(isset($_POST['pass1']) && $_POST['pass1'] != ''){

            // if password length greater than 5
            if(strlen($_POST['pass1']) > 5) {
                $sPass1 = $_POST['pass1'];
            }else{
                $sError .= "[PassLength]";
            }
        }
        // no pass has been set, add to error string
        if($sPass1 == '') $sError .= "[pass1]";

        // check pass 2
        if(isset($_POST['pass2']) && $_POST['pass2'] != ''){
            $sPass2 = $_POST['pass2'];
        }

        // if pass 1 isnt blank and matches that of 2
        if($sPass1 != '' && $sPass1 != $sPass2) $sError .= "[PassMatch]";


        if($sError == ''){
            // success go do something
        }

    }

    // error, go tell the user
    if($sError != ''){

        if(strpos($sError, '[pass1]')){
            echo "no pass1";
        }
        if(strpos($sError, '[PassLength]')){
            echo "Password Length";
        }
        if(strpos($sError, '[PassMatch]')){
            echo "Error, passwords dont match";
        }

    }

答案 1 :(得分:0)

这有助于您:

<script>
  var pass1 = document.getElementById("pass1");
  var pass2 = document.getElementById("pass2");
  pass2.oninput = function(){
         if((pass2.value).length > 0)
             pass1.required = true;
            }  
</script>