开发者

JS regular expression confusion

Firstly apologies for being a tad dim. I need to create a test to check the if the value of an input field.

I currently use /[^A-Za-z0-9 ]/.test(document.form.Serial.value) to test to see if the value o开发者_开发知识库f Serial is alphanumeric only.

Now, if an additional field is set, Serial must either being with 'i' or 'I', then the remaining characters must all be numbers. I had considered doing this with substrings, but it seems a bit long and unnecessary.

Any advice people can give would be very much appreciated!


If you want to test if a string begins with i or I, and then only contain numbers, you could use a regular expression such as this one :

/^[iI][0-9]+$/

Or, for a case-insensitive match :

/^i[0-9]+$/i


Basically, this will match :

  • Beginning of string : ^
  • an i
  • any character between 0 and 9 : [0-9]
    • one or more time : [0-9]+
  • end of string : $


You may try the code below

var test_value = false
if (document.form.Additional_Field.value) {
   test_value = /^(i|I)[0-9]+/.test(document.form.Serial.value) }
else {
    test_value = /[A-Za-z0-9]+/.test(document.form.Serial.value) }

it will result in test_value set to true if Serial is either alphanumeric or if Additional_Field has value true and Serial begins with i or I fallowed by any number of numbers, and test_value set to false otherwise.


Why not break the problem down. You have two valid inputs, so a pattern for syntactically checking the input would be:

/^([iI][0-9]+)|([A-Za-z0-9]+)$/

Then you have a separate, and simpler, problem of determining whether the validated input is appropriate based on the state of the other controls on the form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜