Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox form validation

Tags:

flutter

How can I validate a checkbox in a Flutter Form? Every other validation works fine, but the checkbox doesn't show an Error. Here is my code:

FormField(
  validator: (value) {
    if (value == false) {
      return 'Required.';
    }
  },
  builder: (FormFieldState<dynamic> field) {
    return CheckboxListTile(
      value: checkboxValue,
      onChanged: (val) {
        if (checkboxValue == false) {
          setState(() {
            checkboxValue = true;
          });
        } else if (checkboxValue == true) {
          setState(() {
            checkboxValue = false;
          });
        }
      },
      title: new Text(
        'I agree.',
        style: TextStyle(fontSize: 14.0),
      ),
      controlAffinity: ListTileControlAffinity.leading,
      activeColor: Colors.green,
    );
  },
),
like image 693
Ruslan Avatar asked Nov 26 '18 11:11

Ruslan


People also ask

How do I validate a checkbox?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do I validate a checkbox in HTML?

The Input Checkbox required property in HTML DOM is used to set or return whether the input checkbox field should be checked or not before submitting the form. This property is used to reflect the HTML required attribute. Syntax: It returns the Input Checkbox required property.

Can radio button be validated?

Setup Radio Button Validation To use the above function, call it from within your form validation routine and pass it the radio button group name. It will return the value of the button within the group that is selected, or return a null value if no button in the group is selected.


3 Answers

A cleaner solution to this problem is to make a class that extends FormField<bool>

Here is how I accomplished this:

class CheckboxFormField extends FormField<bool> {
  CheckboxFormField(
      {Widget title,
      FormFieldSetter<bool> onSaved,
      FormFieldValidator<bool> validator,
      bool initialValue = false,
      bool autovalidate = false})
      : super(
            onSaved: onSaved,
            validator: validator,
            initialValue: initialValue,
            builder: (FormFieldState<bool> state) {
              return CheckboxListTile(
                dense: state.hasError,
                title: title,
                value: state.value,
                onChanged: state.didChange,
                subtitle: state.hasError
                    ? Builder(
                        builder: (BuildContext context) =>  Text(
                          state.errorText,
                          style: TextStyle(color: Theme.of(context).errorColor),
                        ),
                      )
                    : null,
                controlAffinity: ListTileControlAffinity.leading,
              );
            });
}
like image 50
Sam3077 Avatar answered Oct 17 '22 20:10

Sam3077


in case if you want to put your checkbox directly in your Form widget tree you can use solution provided below with FormField widget. Instead of using ListTile I used rows and columns as my form was requiring different layout.

FormField<bool>(
  builder: (state) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Checkbox(
              value: checkboxValue,
              onChanged: (value) {
                setState(() {
//save checkbox value to variable that store terms and notify form that state changed
                  checkboxValue = value;
                  state.didChange(value);
                });
              }),
            Text('I accept terms'),
          ],
        ),
//display error in matching theme
        Text(
          state.errorText ?? '',
          style: TextStyle(
            color: Theme.of(context).errorColor,
          ),
        )
      ],
    );
  },
//output from validation will be displayed in state.errorText (above)
  validator: (value) {
    if (!checkboxValue) {
      return 'You need to accept terms';
    } else {
      return null;
    }
  },
),
like image 19
Paul Kastel Avatar answered Oct 17 '22 20:10

Paul Kastel


You could try something like this :

CheckboxListTile(
  value: checkboxValue,
  onChanged: (val) {
    setState(() => checkboxValue = val
  },
  subtitle: !checkboxValue
      ? Text(
          'Required.',
          style: TextStyle(color: Colors.red),
        )
      : null,
  title: new Text(
    'I agree.',
    style: TextStyle(fontSize: 14.0),
  ),
  controlAffinity: ListTileControlAffinity.leading,
  activeColor: Colors.green,
);
like image 10
diegoveloper Avatar answered Oct 17 '22 19:10

diegoveloper