Search code examples
phpyii2yii2-basic-appyii2-validation

Required field not working after including pattern in name - Yii2


I'm passing through awkward situation.

All rules working fine except required field for first_name.

'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'tooShort'=>'First name should contain atleast 3 character'],
'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
'FirstNameRequired' => ['first_name', 'required','message'=>'* First name is required'],
'FirstNameRequired' => ['first_name','match','pattern'=>"/^[a-zA-Z']+$/",'message' => '* First Name can only contain alphabets charater'],

And, It is happening after including pattern in rules. If I remove or comment the pattern rules, it is working.

'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'tooShort'=>'First name should contain atleast 3 character'],
'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
'FirstNameRequired' => ['first_name', 'required','message'=>'* First name is required'],
//'FirstNameRequired' => ['first_name','match','pattern'=>"/^[a-zA-Z']+$/",'message' => '* First Name can only contain alphabets charater'],

My motive was not to allow any space, number, or special character except '. And, this pattern rules working fine as I wanted. But, Only problem is Now it's not taking required rule.

Any Help/Hints/Suggestions are welcome.


Solution

  • Seems you are redefining/overrider the key FirstNameRequired then the last override the previous ..

    i suggest you the use of normal notation for validation rules (without FirstNameRequired key

    ['first_name', 'required','message'=>'* First name is required'],
    ['first_name','match','pattern'=>"/^[a-zA-Z']+$/",'message' => '* First Name can only contain alphabets charater'],