Reputation: 10463
I'm trying to do a validation for the input field and wanted to check if it's a special character or not
so I though I can check that with ASCII value but not sure how is that done in JavaScript language.
In C I can just check with the string of array right away.
if (input < 4 && document.myTable.inputField.value[0] < 65 )
I want to check if it's they have less than four character and those are special characters if yes I will give them an error message else just do nothing.
Upvotes: 0
Views: 3980
Reputation: 122956
You can use the charCodeAt
method of String to determine the ASCII code at a certain position. Assuming that by input
you mean the input field, this would be a way to do it:
var input = document.myTable.inputField.value;
if (input.length < 4 && input.charCodeAt(0) < 65 ) { /* etc. */ }
// examples charCodeAt
'foo'.charCodeAt(0); //=> 102
'-foo'.charCodeAt(0); //=> 45
Upvotes: 1
Reputation: 18359
You can use regular expressions. I think that's easier to read. For example: (/a-z/gi).test(myString)
returns true if myString
contains anything except letters (upper or lower case). So your condition can be changed to:
if (input < 4 && !(/a-z/gi).test(document.myTable.inputField.value))
Upvotes: 2
Reputation: 799150
In C, brute force checking is the cleanest and easiest alternative. In JavaScript, it is not.
js> /^[A-Za-z]+$/.test('foo')
true
js> /^[A-Za-z]+$/.test('bar123')
false
Upvotes: 3