Search code examples
javascripthtmlstringfunctionletters

How can I detect a letter character in JavaScript?


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

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.


Solution

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