admin管理员组

文章数量:1429804

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.

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.

Share Improve this question asked Mar 25, 2012 at 16:52 AliAli 10.5k21 gold badges74 silver badges108 bronze badges 14
  • 1 What do you want to include in "special characters"? – Dogbert Commented Mar 25, 2012 at 16:53
  • 2 Every character is special in its own way. – Ignacio Vazquez-Abrams Commented Mar 25, 2012 at 16:56
  • 1 Well, string-to-string parison with relational operators pares character codes: "@" < "A" === true, "B" < "A" === false. Is that what you're after? – pimvdb Commented Mar 25, 2012 at 17:04
  • 1 It's not a plicated question but "special" is a little bit ambiguous. Anyway, if it's just everything except a-zA-Z then a regular expression is definitely the most readable. – pimvdb Commented Mar 25, 2012 at 17:09
  • 1 @Ali: Yes, but it would be very silly to do so. – Ignacio Vazquez-Abrams Commented Mar 25, 2012 at 17:20
 |  Show 9 more ments

3 Answers 3

Reset to default 3

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

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

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

本文标签: conditional statementsHow to check condition in JavaScript with ASCII valueStack Overflow