如何使用jQuery避免滥用输入?

时间:2018-03-21 06:47:35

标签: jquery validation

我只是学习jQuery而想制作表格。当任何人插入一个滥用的单词/单词时,提交按钮不会被启用,并且输入的输入也将被清除。如果有人能做到这一点,请帮助我。这是我的代码。

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
    <script>
    $(function() {
$("#txt").keyup(function(){ if ($(this).val()) {
$("#btn").removeAttr('disabled');
alert("please enter some valid input");
}
else{$("#btn").attr('disabled','disabled'); }
});
});
 </script>  

</head>
<body>
<input type="text" id="txt" />

<input type="submit" id="btn" disabled />

</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以使用一系列单词来过滤所有滥用的单词。然后使用regular expression测试输入是否有效。

这是我的尝试:

var arr = [ "bad", "ugly" ],
  regex = new RegExp('\\b' + arr.join("\\b|\\b") + '\\b', 'i');


$(function() {

  $("#txt").keyup(function() {

		if(!regex.test(this.value)){ 
      $("#btn").removeAttr('disabled');
    } else {
    	alert("You enter a bad word!");
      $("#btn").attr('disabled', 'disabled');
    }
    
    if( !$("#txt").val()){
      $("#btn").attr('disabled', 'disabled');
		}
    
  });
  
   $("#clear").on("click", function() {
            $("#txt").val("");
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt" />

<input type="submit" id="btn" disabled />
<input type="button" id="clear" value="Clear"/>

相关问题