Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a drop down list in Laravel PHP?

Tags:

php

laravel

The Situation:

Under models, I've a user.php which handles all validation regarding adding a user to a website.

This is (part of) the code:

public static $add_rules = array(
   'last_name'             => 'required',
   'first_name'            => 'required',
   'email'                 => 'required|unique:users,email',
   'username'              => 'required|alpha_num|min: 5|unique:users,username',
   'password'              => 'required|min: 4|same:password_confirmation',
   'password_confirmation' => 'required',
   'user_role'             => 'required|not_in:-- Choose User Type --'
);

user_role is the ID of the dropdown list, seen here:

<select name="user_type_id" class="form-control" id="user_role">
<option value="0">-- Choose User Type --</option>
@if(Session::get("user_type") == "superuser")
     {
     @foreach($user_types as $ut)
         <option value="{{$ut['id']}}">
             {{ ucwords($ut["user_type"]) }}
         </option>
     @endforeach
     }
@else{
     <option value="Regular">Regular</option>
}@endif
</select>

Basically, what happens up there is that the drop down list is filled with user types, whatever they are. But it always has the first 'option' of -- Choose User Type --.

The Problem:

Problem is, the user can go with that option and add a user. I have a javascript code that blocks this and outputs an error message in a pop-up window, but it's ugly, and not consistent with the rest of the website's error messages.

So I added it to the rules. It needs to be validated such that it will only accept anything other than the default -- Choose User Type -- option.

What I Tried:

not_in did not work, unfortunately.

Can I get some help on this?

Thanks.

like image 318
zack_falcon Avatar asked Jul 02 '14 03:07

zack_falcon


2 Answers

You're not using not_in the right way. You're supposed to pass in the values that are not allowed, not the representation of those values.

'user_role' => 'required|not_in:0'
like image 192
Kemal Fadillah Avatar answered Oct 01 '22 22:10

Kemal Fadillah


You have your select named "user_type_id" but you are trying to validate a field named "user_role"

like image 28
CleverCookie Avatar answered Oct 01 '22 22:10

CleverCookie