用javascript检查验证


Check validation with javascript

我发现了几个主题有同样的问题,但我不知道如何适应我的例子。

我有这样一个登录表单:

<form action=do_login.php?id= method=post>
                    <label>Enter your Frequent Diner ID</label><br>
                    <div class="shake-id">
                        <input id="fd-id" class="login-input" type="text" name=loginid value="" maxlength="8" placeholder="Frequent Diner ID" /><br>
                    </div>
                    <div class="id-alert" style="display: none;">Your Frequent Diner ID must have 8 digits. Check and try again</div>
                    <label>Enter your Password</label><br>
                    <div class="shake-pass">
                        <input id="pass" class="login-input" type="password" name=password value="" maxlength="20" placeholder="Password" /><br>
                    </div>
                    <input type=hidden name=call_from value="login.php">
                    <input type=hidden name=forward_url value="<?PHP echo urlencode(@$_REQUEST["forward_url"])?>"><br><br>
                    <input type=submit value="Login">
</form>

那么我有这个文件来做登录:

<?php
require_once( "config.php");
require_once( PATH_FUNCTION."/check_permission.php");

//default login fail landing page
$redirect = (isset($_REQUEST['call_from']))?PAGE_LOGINFAIL:PATH_PUBLIC;
$errcode = "err1";
$forward_url = "";
if (strlen($_REQUEST['loginid'])>0&&strlen($_REQUEST['password'])>0)  {
unset($_SESSION["user"]);                                                                 
$fields = array(
    "loginid"   => @$_REQUEST['loginid'],
    "password"=> @$_REQUEST['password']
    );
$user = new user("cuisine_user",$fields);
$data=$user->login();
if ($data&&$data["login_fail"]==0) {
  $errcode = "err0";
  $redirect=(@$_REQUEST['forward_url'])?urldecode(@$_REQUEST['forward_url']):PATH_PUBLIC;
  //get session
  $session=new session();
  $_SESSION["site_".SITE."_id"]=$session->newSession();
  //get user session
  $_SESSION["user"]=$data;

  $set_f = array("login_count"=>1+$data['login_count'],"login_fail"=>0);
  $where_f = array("id"=>$data['id']);
  $user->update($set_f,$where_f);

  if (isset($_REQUEST['forward_url'])){
    $_SESSION["logout_url"] = PATH_PUBLIC;
  }
  else{
    if (isset($_SESSION['preview_mode']) && $_SESSION['preview_mode'])
        $_SESSION["logout_url"] = PATH_PUBLIC."?mode=1";
    else
        $_SESSION["logout_url"] = PATH_PUBLIC;
  }
  if (isset($_REQUEST['forward_url']))
   header('Location: '.$redirect); 
   echo "200:".$_SESSION["user"]["username"];
}
else
{  
  // add login fail by 1
  if ($data['login_fail']>0){
  $set_f = array("login_fail"=>$data['login_fail']);
  $where_f = array("id"=>$data['id']);  
  //$user->update($set_f,$where_f);
  }
  $forward_url = (@$_REQUEST['forward_url'])?'&forward_url='.urldecode(@$_REQUEST['forward_url']):'';
    if (isset($_REQUEST['forward_url']))
    header('Location: '.$redirect."?code=".$errcode.$forward_url);
  echo "300";
}
}
else {
  $forward_url = (@$_REQUEST['forward_url'])?'&forward_url='.urldecode(@$_REQUEST['forward_url']):'';
    if (isset($_REQUEST['forward_url']))
  header('Location: '.$redirect."?code=".$errcode.$forward_url);
  echo "400";
}
die();
?>

最后这个脚本检查字段:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
//BLOCK THE LETTERS AND DOT/SLASH/ETC IN FD NUMBER
$(document).ready(function() {
    $("#fd-id").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
}); 
//CHECK WHEN CUSTOMER SUBMIT
$('form').submit(function () {
    var value = document.getElementById('fd-id').value;
    if (value.length !== 8) {
        $('.shake-id').effect( "shake" );
        $('.id-alert').fadeIn('slow');
        $('#fd-id').addClass('input-wrong');
        return false;
    }
});
//ACTIVATE FUNCTION VALIDATE
$("#fd-id").on('input', validate);
//CLEAN THE WRONG MESSAGE IF THE CUSTOMER TYPE ALL THE DIGITS
function validate() {
    var value = document.getElementById('fd-id').value;
    if (value.length == 8) {
        $('.id-alert').fadeOut('slow');
        $('#fd-id').removeClass('input-wrong');
    }
    else if (value.length == 0) {
        $('.id-alert').fadeOut('slow');
    }
}
</script>

现在我想用javascript验证密码和logingid在同一个文件比我有我的表单。所以我可以添加一些友好的效果,就像我现在有的。什么好主意吗?因为如果切换到另一个文件我就不能添加效果了

我认为您采用了错误的输入验证方法。可以把它想象成一组用户必须遵守的规则,只要有错误,表单就不会被发送。

你不应该屏蔽字符之类的。让用户随心所欲地填写,当输入更改焦点和用户尝试提交时,您可以验证(或标记为错误)输入。

现在您可以通过多种不同的方式实现这一点,但今天将服务器端和客户端工作分开是很流行的。客户端有一个完整的检查系统是很好的,当一切正常时,你把它发送到服务器进行更多的检查。

表单验证器采用完全相同的方法。由于您正在使用jQuery,您不妨使用validator。有许多不同的存在:

  • jqueryvalidation
  • formvalidator
  • jquery-validation

它们的工作方式都差不多。我个人使用了第一个。

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script>
$("#commentForm").validate();
</script>

如果你想尝试一下,下面就是它的实际效果