String pattern for checking the first 8 characters are same in luci

330 views Asked by At

I am using Luci-Lua in openWRT. I need a function to validate the password field that only accepts alphanumeric and the first 8 characters are not same. Please check my code and help me.

function pw1.validate(self, value)
  if #value <= 6 and not value:find('^[%-%.%w]+$') then
    return nil
  end

  if value:match("^(.)\1*$") then
     return nil
  end

  return value
end
1

There are 1 answers

0
wp78de On

The central point of your question is: The pinnacle of your question is

the first 8 characters are not same

As suggested, this can be done with a Lua pattern (similar to a regex). If you want to check if the first 8 characters are all the same you could use

function validate1st8NotSame(value)
    if value:match("^(.)%1%1%1%1%1%1%1") then
      return false
    end
    return true
end

print(validate1st8NotSame("aaaaaaaa")) --not valid
print(validate1st8NotSame("aaaaaaab")) --valid
print(validate1st8NotSame("aaaaaaa")) --!?

The pattern works like this:

  • ^(.) capture the character at position 1,
  • %1%1%1%1%1%1%1 use a back reference %1 to it to check the capture repeats 8 times.

If you actually want to check whether the first 8 characters do not contain an identical character then a bit more complicated pattern is needed:

function validate1st8NoSame(value)
    if value:sub(1,8):match("(.).-%1") then
         return false
    end
    return true
end

print(validate1st8NoSame("abcdefghe")) --valid
print(validate1st8NoSame("abcdefgae")) --invalid

The idea here is:

  • value:sub(1,8) get the first 8 characters
  • (.) capture a single char
  • .- matches the shortest possible sequence of 0 or more repetitions of any characters ;
  • %1 backreference to the captured character

The following regex demo that applies the same logic hopefully makes is more tangible.

Sample Code