如果输入包含除字母以外的任何其他符号,则显示div

时间:2017-09-13 11:51:29

标签: javascript jquery forms

我有一个简单的名/姓名表。提交时,我想检查是否只使用了字母,如果没有,则显示错误div。

例如:

if ('#input-32' ) {
    /* contains anything other than letters */
    $("#error").show(); 
}

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式 - Read More

const input = document.querySelector('#firstname');

input.addEventListener('input', function(e) {
	const val = e.target.value;
	const isLetter = /^[a-zA-Z]+$/.test(val);
	console.log(isLetter);
        // if( isLetter ){ ... }
})
<input type="text" id="firstname">

答案 1 :(得分:0)

如果输入包含除字母以外的任何内容,则以下内容应显示错误元素:

if ($('#input-32').val().match(/[^a-zA-Z]/g)) {
  /* contains anything other than letters */
  $("#error").show(); 
}

答案 2 :(得分:0)

$(document).ready(function(){
  $("#error").hide();
  $("#nameField").on("change", function(){
    var nameSub = $('#nameField').val();
    if(/^[a-zA-Z]+$/.test(nameSub)){
      $("#error").hide();
    }
    else{
      $("#error").show();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="name" id="nameField"/>
<div id="error">error</div>