【问题标题】:Why is my input validation from jquery wont work?为什么我的 jquery 输入验证不起作用?
【发布时间】:2019-12-23 09:14:45
【问题描述】:

我想从输入表单中验证 onkeyup,我制作了一个 jquery。我很难找到它为什么不检查?我需要去一个php页面检查。我的代码不能正常工作可能有什么问题?

<html>
<head>
<title>
reg
</title>
</head>
<body>
<form method="post">
<input type="text" name="name" onkeyup="check_user()" id="name"/><div id="checking">Checking</div>
<button type="submit" name="submit">Submit<button> 
</form>


<script src="jquery-3.3.1.min.js"></script>
<script>
document.getElementById("submit").disabled=true;
function check_user(){
    var name = document.getElementById("name").value;

     $.post("user_check.php",
     {
         user: name
     },
     function(data,status){
         if(data=='<p style="color:red">Name contains a number</p>'){
             document.getElementById("submit").disabled=true;
         }
         else{
             document.getElementById("submit").disabled=false;
         }
         document.getElementById("checking").innerHTML=data;    
     }

     );

}
</script>
</body>
</html>

user_check.php

<?php
if (isset($_POST['user'])) {    
    if(preg_match('/^\d+$/', $_POST['user'])) {
        echo '<p style="color:red">Name contains a number</p>';
    } else {
        echo '<p style="color:green"> You can take this name</p>';
    }    
}
?>

【问题讨论】:

  • 你能定义不工作吗?发生了什么?
  • cheking这个词不会变

标签: javascript php validation input


【解决方案1】:

1-先添加提交按钮的id属性id="submit"这样

<button type="submit" id="submit" name="submit">Submit<button>

2- 更新 user_check.php 上的代码

if (isset($_POST['user'])) {    
if(!preg_match('/^([^0-9]*)$/', $_POST['user'])) {
    echo '<p style="color:red">Name contains a number</p>';
} else {
    echo '<p style="color:green"> You can take this name</p>';
}    
}

【讨论】:

    【解决方案2】:

    您可以通过添加类似这样的模式属性来验证文本框 pattern="[a-zA-Z]+"

      <input type="text" name="name" pattern="[a-zA-Z]+"  title="please just add strings"  id="name"/>
    

    我还注意到在您的代码中您没有为提交按钮添加 id,这就是您的提交按钮未被禁用的原因,您的代码应该像提交按钮一样。 提交

    【讨论】:

    • 这只是 UI 验证。 OP 希望为服务器端验证执行 AJAX。它们并不完全相同。
    • 请先像这样添加提交按钮的id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多