需要帮助只需验证字段是否仅为文本

时间:2012-05-24 17:53:21

标签: javascript

现在我有(这是来自另一个已经完成的功能)

function validatelength() {
    var length = parseInt(document.getElementById("length").value, 10);
    var lengthError = document.getElementById("lengthError");
    if (isNaN(length) || length < 50 || length > 220) {
        lengthError.innerHTML = ">>Please enter your height<<";
        return false;
    } else {
        lengthError.innerHTML = "";
    }
    return true;
}

这是我的小代码,用于检查字段是否包含人的长度。

现在我想要一个文本字段(名字/名字/备注) 到目前为止我已经

function validatetext() {
    var text = parseInt(document.getElementById("text").value, 10);
    var textError = document.getElementById("textError");
    if (isNaN(text) || text < 50 || text > 220) {
        textError.innerHTML = ">>Please enter text only<<";
        return false;
    } else {
        textError.innerHTML = "";
    }
    return true;
}

有人可以帮我完成这项功能吗?谢谢 顺便说一句:我不能使用jquery。 (不允许)

4 个答案:

答案 0 :(得分:3)

使用正则表达式确保只在字母中出现字母。

类似

/^[A-Za-z]*$/

应该有效。那个正则表达式说

“匹配来自A-Z和a-z的任何字母,从0到无限次,从行的开头到行尾”。

我假设你不想接受任何不是字母的东西。

答案 1 :(得分:1)

假设textError是您正在评估的字符串,并且应该是纯文字的,我建议:

if (textError.match(/\d/)){
    // there's numbers in this string
}

JS Fiddle proof-of-concept

参考文献:

答案 2 :(得分:0)

看,这个实现可以帮助你整个生活,如果你是一名学生,它比正则表达式更容易解释。

//In this case I will define here the lower and upper case alphabet
//you can restrict this alphabet to match commas, spaces, or anything else, you just
//need to add them to the var.

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"; 
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ";

//This function will check if an specific letter "c" exist in the previous defined
//alphabet
function isLetter (c) 
{ 
    return( ( uppercaseLetters.indexOf( c ) != -1 ) || 
            ( lowercaseLetters.indexOf( c ) != -1 ) ) 
} 


//this is the Main Method, basically their function is split the Word "s" in all chars
//and check if those chars are defined in 
//the initials vars lowercaseLetters and uppercaseLetters

function isAlphabetic (s) {
   var i; 


    for (i = 0; i < s.length; i+=1) 
    {    
        // Check that current character is letter. 
        var c = s.charAt(i); 

        if (!isLetter(c)) 
        return false; 
    } 
    return true; 
} 

现在,要调用此函数非常简单,只需要从Input中捕获文本并调用isAlphabetic(text),其中text是捕获的文本。

答案 3 :(得分:0)

<SCRIPT LANGUAGE="JavaScript">

function checkIt(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (!((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))) {
       document.getElementById("lengthError").innerHTML = "This field accepts numbers only."
        return false
    }
    document.getElementById("lengthError").innerHTML = ""
    return true
}

</SCRIPT>

<INPUT TYPE="text" NAME="text" onKeyPress="return checkIt(event)">
相关问题