1
votes

I'm new to Laravel and am trying to figure out how to validate user input.

I have a form with several text fields, a textarea and a checkbox:

      {{ Form::text('firstname', '', ['placeholder' => 'First Name', 'class' => 'form-control']) }}
      {{ Form::text('lastname', '', ['placeholder' => 'Last Name', 'class' => 'form-control']) }}
      {{ Form::email('email', '', ['placeholder' => 'Email', 'class' => 'form-control']) }}
      {{ Form::textarea('question', '', ['placeholder' => 'Question', 'class' => 'form-control']) }}
      {{ Form::checkbox('terms_and_conditions', 'yes') }}
      {{ Form::label('terms_and_conditions', 'I agree to terms and conditions') }}

The validation rules are:

  public static $rules = array(
    'firstname' => 'required|between:2,20',
    'lastname' => 'required|between: 2,30',
    'email' => 'required|email',
    'question' => 'required|max: 5000',
    'terms_and_conditions' => 'required|accepted',
  );

The text fields are all validating as expected, but I cannot get the checkbox field to validate. I echoed the json of $input to the view and can verify that the model is receiving the terms_and_conditions checkbox value, so I don't understand why it won't validate?

If I add any new fields or change a field's name those fields won't validate as well.

Am I missing something?

1
Do you need to have both required and accepted as rules? If accepted is a rule then doesn't that get the job done?Mitch
Also the following error message is generated. "The terms and conditions must be accepted." and this is the $input returned to the view: {"firstname":"Test","lastname":"User","email":"test@user.com"} (I took out the _token bit for clarity)Jeremy Plack
@MitchGlenn, I don't think so, I have tried it with and without the required. I thought accepted was all that was needed. I'm really puzzled because if I add any new fields and rules now they have the same problem of not validating.Jeremy Plack
try replacing the yes with 1 for true, {{ Form::checkbox('terms_and_conditions', 1) }}Mitch
I have tried using 1, 'yes' and 'on', none have worked. I don't think it is an issue with the checkbox itself, because I have replaced that field entirely with radio buttons, and other inputs just to test and none of them will validate, only the fields with names that I had prior to adding the checkbox field will validate.Jeremy Plack

1 Answers

2
votes

I just realized there was a glaring noob error in my model. I neglected to add terms_and_conditions as a fill-able field. The form now validates properly, this begs another question though, is it possible to exclude that field from being added to the database? I'd rather not have that column in the database but Laravel throws an exception without it.