最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How can I detect a letter character in JavaScript? - Stack Overflow

programmeradmin6浏览0评论

I have a number of HTML inputs in a website. 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)

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. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input bees 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 es from the value of my input; and if there is, the function would return 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.

Note

Please use pure JavaScript only. No jQuery or other libraries/frameworks.

I have a number of HTML inputs in a website. 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)

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. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input bees 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 es from the value of my input; and if there is, the function would return 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.

Note

Please use pure JavaScript only. No jQuery or other libraries/frameworks.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Sep 6, 2015 at 20:21 user5171952user5171952 1
  • Just to let you know, if you are truly checking if the value of a number input element is a valid number or not, if it is invalid the returned value will be an empty string. This means that it is impossible to check the validity of the returned string if in fact the input's value is invalid. See my answer below for the correct method of checking an input element's validity. – user4639281 Commented Sep 7, 2015 at 13:59
Add a ment  | 

7 Answers 7

Reset to default 4

You can use isNaN() function to make your own function that check if the given string is numeric :

//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. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input bees 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. 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

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.

If a number input's value is invalid, it will return an empty string.

This means that you cannot pare 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.

<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/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):

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).

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

You could try this I found on the filter page of developer 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).

you can get a list of obj from a string with theString.split('')

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)

发布评论

评论列表(0)

  1. 暂无评论