简体   繁体   English

如何在JavaScript中检测字母字符?

[英]How can I detect a letter character in JavaScript?

I have a number of HTML inputs in a website. 我在网站上有很多HTML输入。 They are inside a form, but the form is not submitted to the server. 它们位于表单内,但表单未提交给服务器。 Rather, values of the assorted inputs (number inputs, text inputs, and check boxes) are used to ultimately 'stitch together' a product code based on the inputs and selected options. 相反,各种输入(数字输入,文本输入和复选框)的值用于最终根据输入和所选选项将产品代码“拼接”在一起。 (using JavaScript) (使用JavaScript)

My problem is this: while the number input 我的问题是这样的:输入的数字

<input type='number'/>

only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. 在服务器端提交时只使用数字值,我使用JavaScript来检查不同输入的各种值。 This allows for a letter (alphabet) character to be put in the number input. 这允许将字母(字母)字符放入数字输入中。 IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called. 如果您这样做,输入将以红色标出,但它仍然允许将产品代码拼接在一起的功能被调用。

What I need is a way to detect if a given string contains an alphabetical character, instead of just numbers. 我需要的是一种检测给定字符串是否包含字母字符而不仅仅是数字的方法。 My idea was something like this: 我的想法是这样的:

<input type='number' id='inp' />
<script>
input=document.getElementById('inp');
val=input.value;
checkforletters(val);
input.onchange=function(){
  if(checkforletters){
//resetting the value to blank if there is an alphabet character in the string
    input.value='';
  }
}
</script>

You'll notice that there is a function in there called 你会注意到那里有一个函数叫做

checkforletters()

I have not written it. 我还没写过。 This function would check and see if there is an alphabet character inside the string that comes from the value of my input; 此函数将检查并查看字符串中是否存在来自输入值的字母字符; and if there is, the function would return true. 如果有,则该函数将返回true。

This function is what I need. 这个功能是我需要的。 The rest of the code resets the value of the input to blank if there is an alphabet character. 如果存在字母字符,则其余代码会将输入的值重置为空白。

So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise. 因此,总而言之,我需要的是一个函数,当传递一个字符串作为参数时,如果其中有字母,则返回true,否则返回false。

Note 注意

Please use pure JavaScript only. 请仅使用纯JavaScript。 No jQuery or other libraries/frameworks. 没有jQuery或其他库/框架。

You can use isNaN() function to make your own function that check if the given string is numeric : 您可以使用isNaN()函数创建自己的函数来检查给定的字符串是否为数字:

//Will return true if the given string is number, false if is contain characters
function isNumeric(yourString){
    return !isNaN(yourString)
}

Hope this helps. 希望这可以帮助。

My problem is this: while the number input only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. 我的问题是:虽然数字输入只允许在服务器端提交时使用数字值,但我使用JavaScript来检查不同输入的各种值。 This allows for a letter (alphabet) character to be put in the number input. 这允许将字母(字母)字符放入数字输入中。 IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called. 如果您这样做,输入将以红色标出,但它仍然允许将产品代码拼接在一起的功能被调用。

You can utilize the built in HTML5 constraint validation with JavaScript. 您可以使用JavaScript 内置的HTML5约束验证 This means that instead of having to check whether the value is valid, the value can never be invalid to begin with. 这意味着,不必检查值是否有效,该值永远不会无效。

The following example will disallow any invalid input at the user level. 以下示例将禁止用户级别的任何无效输入。 It does this by checking the validity then storing the value for future use if it is valid or, if the value is not valid, setting the value to the previously stored valid value if there is one, an empty string if not. 它通过检查有效性然后存储值以供将来使用(如果有效)或者如果值无效,则将值设置为先前存储的有效值(如果有),如果不存在则设置为空字符串。

This means that the value can never be invalid. 这意味着该值永远无效。

 <input type="number" oninput="(validity.valid&&(dataset['prev']=value))||(value=dataset['prev'])"> 

The following is the same method, without using inline JavaScript 以下是相同的方法,不使用内联JavaScript

 document.getElementById('test').oninput = function() { if(this.validity.valid) this.dataset['prev'] = this.value; else this.value = this.dataset['prev']; } 
 <input type="number" id="test"> 

So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise. 因此,总而言之,我需要的是一个函数,当传递一个字符串作为参数时,如果其中有字母,则返回true,否则返回false。

If a number input's value is invalid, it will return an empty string. 如果数字输入的值无效,则返回空字符串。

This means that you cannot compare the returned value to check it's validity, because if it is in fact invalid the returned value will be an empty string. 这意味着您无法比较返回值以检查其有效性,因为如果它实际上无效,则返回的值将为空字符串。

The following example shows that even if the value is invalid, checking it with isNaN won't show you that, nor will any of the other methods mentioned here. 以下示例显示即使该值无效,使用isNaN检查它也不会显示该信息,也不会显示此处提到的任何其他方法。

 <input type="number" oninput="document.getElementById('value').textContent = value; document.getElementById('isnum').textContent = !isNaN(value)"><br> Returned Value: <span id="value"></span><br> Is a number: <span id="isnum"></span> 

If you really want to validate the input element while running your script , you can check the input element's validity at that time. 如果您确实希望在运行脚本时验证输入元素,则可以在此时检查输入元素的有效性。

 var test = document.getElementById('test'); document.getElementById('button').onclick = function(e) { if(!test.validity.valid) { alert('Its Invalid!'); } else { alert('Its valid!'); } } 
 <input id="test" type="number"><button id="button">Check It</button> 

Alternatively, if your input elements are inside a form and you run your script on the form submission event, it will automatically validate for you, and disallow submission unless the value is valid. 或者,如果您的输入元素位于表单内,并且您在表单提交事件上运行脚本,它将自动为您验证,并禁止提交,除非该值有效。

 var test = document.getElementById('test'); document.getElementById('form').onsubmit = function(e) { e.preventDefault(); alert("Its valid!"); // this will only happen if the inputs are valid. } 
 <form id="form"><input id="test" type="number"><button>Check It</button></form> 

Use a regular expression that matches any non-digits. 使用匹配任何非数字的正则表达式。

var myString = 'aaaaa1';
var reg = new RegExp(/\D+/); 
console.log(reg.test(myString));
// true

here is simplest way- handle onkeyup:( http://jsfiddle.net/vittore/g7xe0drp/ ) 这里是最简单的方法处理onkeyup :( http://jsfiddle.net/vittore/g7xe0drp/

var inp2= document.getElementById('inp2')

inp2.onkeydown = onlyNumbers

function onlyNumbers(e) { 
    console.log(e)
    if (e.which <=49 || e.which >=57) {
        e.preventDefault()
        return false;
    }

}

Check that string contains only numbers (\\d): 检查字符串是否只包含数字(\\ d):

function checkforletters(val) {
    var pattern = /^\d+$/;
    return pattern.test(val);
}

If you need other characters beside numbers instead of \\d use [\\d,-] (, and - are characters that you want to allow). 如果您需要数字旁边的其他字符而不是\\d使用[\\d,-] (和, - 是您要允许的字符)。

Please use this to check for alphabets or special characters in your input: 请使用此选项检查输入中的字母或特殊字符:

checkforletters(val){
    var pattern = /[\D]+/

    if (pattern.test(val)) {
        // val contains a non-digit character, it contains alphabet or special character
    }
    else{
    // val only contains digits
    }
}

pattern.test(val) will only return true if val contains alphabet 如果val包含字母,pattern.test(val)将仅返回true

You could try this I found on the filter page of developer mozilla org. 你可以试试这个我在开发者mozilla org的过滤器页面上找到的。

function isNumber(obj) {
  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}

array filter 阵列过滤器

Of course you will need to rework it a little to make isString(), you could try typeof(obj) === 'string' && isNaN(obj). 当然你需要重做一点才能使isString(),你可以尝试typeof(obj)==='string'&& isNaN(obj)。

you can get a list of obj from a string with theString.split('') 你可以从字符串中获取一个带有theString.split('')的obj列表

For example: 例如:

 let s = 'Is this 1 or 2 and not 3 strings? .! : ' let c = s.split('') let d = c.map((c,i) => { let v = typeof(c) === 'string' && isNaN(c) ? 'string': 'not-string' return {c, v} }) console.log(d) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM