Regular expression in Laravel

Asked

Viewed 789 times

3

I’m not very good at regex but using the site https://regex101.com I was able to generate an expression that accepts:

  • Do not accept special characters
  • Can have up to 5 words separated by whitespace

Follow the generated regex: (^\w{0,30}){1}(\s?(\w{0,30})){1,4}

I’m trying to use it in a Request class as a Rule regex

public function rules()
{
    return [

        'name' => 'required|max:255|unique:classes,name|regex:/(^\w{0,30}){1}(\s?(\w{0,30})){1,4}/m',
        'description' => 'max:255',

    ];
}

This is not being validated, anything I enter in the 'name' field the system accepts.

  • 1

    Have you read the documentation ? Documentation says that if using regex validation you may have to use an array instead of separating each rule with |. I would start by testing this. Note from documentation: "Note: When using the regex / not_regex Patterns, it may be necessary to specify Rules in an array Instead of using pipe delimiters, especially if the regular Expression contains a pipe Character."

  • Yeah, I read that and I called the validate() function by array, but the same thing happened. I think it’s the regex syntax problem, because I took all the symbols and put them in a simpler regex and it worked. It is this solution that will stay for now (laughs)

  • 1

    That’s because your regex is probably not correct. The regex you have will validate if you have 6 words for example, because you don’t indicate that you can’t have anything after 5 word. See this regex of yours in regex101. To correct this detail just add a $ at the end of the regex to indicate that it has to end there and there can be nothing else ahead. Now only you know the cases where the regex is failing where it shouldn’t

  • Wow! kkkk was just putting $/at the end of the regex

  • Thank you, Isac! How do you score your answer?

  • 1

    I did not answer right away I can not score/accept, but I can put an answer if you prefer, to leave the question finished.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.