简体   繁体   中英

Why is my input validation from jquery wont work?

I want a validation onkeyup from an input form, I've made a jquery. I'm having a hard time finding why is it not checking? I need to go to a php page in checking. What could be wrong to my code that it don't work?

<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>';
    }    
}
?>

You can validate the text box by adding the pattern attribute like this pattern="[a-zA-Z]+"

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

i also notice in your code you did not add the id for the submit button thats why your submit button is not disabled, your code should like this for submit button. Submit

1- first add the id attribute of the submit button id="submit"like this

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

2- update the code on 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>';
}    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM