RegExp:如何只匹配字母

时间:2018-01-22 05:20:09

标签: javascript regex

我一直在尝试在var letters中添加此错误检查部分另外8行,但是当我添加这些行时,它似乎完全破坏了我的整个错误检查。

总结

var letters = /^[A-Za-z]+$/;
if(username.value.match(letters)) {
  myerror += "Username is good. <br>"; 
 } else {
  myerror += "Username can only have letters. <br>"; 
 }

更多背景信息:

<script>
    function valfunc() {

        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var confirm = document.getElementById("confirm").value;
        var age = document.getElementById("age").value;
        var myerror = "";

        if (username.length == 0) {
            myerror += "Username field has been left blank. <br>";
        }

        if (password.length == 0) {
            myerror += "Password field has been left blank. <br>";
        }

        if (confirm.length == 0) {
            myerror += "Confirm field has been left blank. <br>";
        }

        if (age.length == 0) {
            myerror += "Age field has been left blank. <br>";
        }

        if ((username.length < 5) || (username.length > 15)) {
            myerror +=
                "Username should be between 5 and 15 characters long. <br>";
        }

        if (password !== confirm) {
            myerror += "Password and Confirm input text box values should match. <br>";
        }

        var letters = /^[A-Za-z]+$/;
        if (username.value.match(letters)) {
            myerror += "Username is good. <br>";
        } else {
            myerror += "Username can only have letters. <br>";
        }

        if (age <= 0) {
            myerror += "Age should be a positive integer. <br>";
        } else {
            if ((age < 18) || (age > 110)) {
                myerror += "Age should be between the values 18 and 110. <br>";
            }
        }

        document.getElementById("output").innerHTML = myerror;

        if (myerror.length > 1) {
            return false;
        } else {
            return true;
        }

    }
</script>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed  -->
</script>

2 个答案:

答案 0 :(得分:0)

删除username.value使用用户名。你没有使用确切的username.value应该是undefined它会在你使用时抛出错误 username.value.match()

var letters = /^[A-Za-z]+$/;
if(username.match(letters))
 {
  myerror += 
  "Username is good. <br>"; 
 }
 else{
  myerror += 
  "Username can only have letters. <br>"; 
 }

答案 1 :(得分:0)

这就是错误

if(username.value.match(letters))

username是字符串,而不是对象,因为您已从对象中获取值

var username = document.getElementById("username").value;

这就是为什么它会给出错误,它应该是

if(username.match(letters))