答案 0 :(得分:1)
您可以使用Regex in JavaScript来实现此目标......
var text = document.getElementById('TEXTBOX_ID').value;//get value from textbox
var regex = /^[a-zA-Z]+$/;//only allow letters (minimum of 1). No whitespace, no symbols, no numbers
if(regex.test(text)){
//this is valid
}
答案 1 :(得分:1)
试试这样:
<script type="text/javascript">
var cek = /^[a-zA-Z\ \']+$/;
function validate(form){
var name = form.name.value;
if (!cek.test(name)) {
alert("Only Alphabetic");
return false;
}
return true;
}
</script>
<form method="" action="#" onSubmit="return validate(this);" name="form">
<input type="text" id="name" name="name" value="" />
<input type="submit">
</form>
答案 2 :(得分:-1)
创建一个函数:
function validateTextbox(element) {
var pattern = /^[A-Za-z]+$/;
if (!pattern.test(element.innerHTML) {
//Do something
element.innerHTML += " Not matched";
}
}
将它绑定到元素:
<some-element onchange="validateTextbox(this)" />
或者使用(更容易维护和推荐)方式绑定它:
var element = getElementById("someID");
element.addEventListener("change", function() {
var pattern = /^[A-Za-z]+$/;
if (!pattern.test(element.innerHTML) {
//Do something
element.innerHTML += " Not matched";
}
}
}