why condition is always true in javascript?

  • A+
Category:Languages

Could you please tell me why my condition is always true? I am trying to validate my value using regex.i have few conditions

  1. Name should not contain test "text"
  2. Name should not contain three consecutive characters example "abc" , "pqr" ,"xyz"
  3. Name should not contain the same character three times example "aaa", "ccc" ,"zzz"

I do like this

https://jsfiddle.net/aoerLqkz/2/

var val = 'ab dd'  if (/test|[^a-z]|(.)/1/1|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/i.test(val)) {                        alert( 'match')                     } else {    alert( 'false')    } 

I tested my code with the following string and getting an unexpected result

  1. input string "abc" : output fine :: "match"
  2. input string "aaa" : output fine :: "match"
  3. input string "aa a" : **output ** :: "match" why it is match ?? there is space between them why it matched ????

    input string "sa c" : **output ** :: "match" why it is match ?? there is different string and space between them ????

 


The issue is the [^a-z]. This means that any string that has a non-letter character anywhere in it will be a match. In your example, it is matching the space character.

The solution? Simply remove |[^a-z]. Without it, your regex meets all three criteria.

  1. test checks if the value contains the word 'test'.
  2. abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz checks if the value contains three sequential letters.
  3. (.)/1/1 checks if any character is repeated three times.

Complete regex:

/test|(.)/1/1|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/i` 

I find it helpful to use a regex tester, like https://www.regexpal.com/, when writing regular expressions.

NOTE: I am assuming that the second criteria actually means "three consecutive letters", not "three consecutive characters" as it is written. If that is not true, then your regex doesn't meet the second criteria, since it only checks for three consecutive letters.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: