elwin luo
elwin luo

Reputation: 15

Flutter TextFormField Validation using constructor to call in one page error

I have 3 constructor class

Textformfield.dart
Validator.dart
Signin.dart

Here is textformfield.dart

class CustomTextField extends StatelessWidget {
  final String hint;
  final TextEditingController textEditingController;
  final TextInputType keyboardType;
  final bool obscureText;
  final IconData icon;
  final Validator validator;
  double _width;
  double _pixelRatio;
  bool large;
  bool medium;

  CustomTextField({
    this.hint,
    this.textEditingController,
    this.keyboardType,
    this.icon,
    this.obscureText = false,
    this.validator,
  });

  @override
  Widget build(BuildContext context) {
    _width = MediaQuery.of(context).size.width;
    _pixelRatio = MediaQuery.of(context).devicePixelRatio;
    large = ResponsiveWidget.isScreenLarge(_width, _pixelRatio);
    medium = ResponsiveWidget.isScreenMedium(_width, _pixelRatio);
    return Material(
      borderRadius: BorderRadius.circular(30.0),
      elevation: large ? 12 : (medium ? 10 : 8),
      child: TextFormField(
        autovalidate: true,
        controller: textEditingController,
        keyboardType: keyboardType,
        cursorColor: Colors.orange[200],
        decoration: InputDecoration(
          prefixIcon: Icon(icon, color: Colors.orange[200], size: 20),
          hintText: hint,
          border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(30.0),
              borderSide: BorderSide.none),
        ),
      ),
    );
  }
}

Her is my validator.dart code

class Validator {
  String validateName(String value) {
    String pattern = r'(^[a-zA-Z ]*$)';
    RegExp regExp = new RegExp(pattern);
    if (value.length == 0) {
      return "Name is Required";
    } else if (!regExp.hasMatch(value)) {
      return "Name must be a-z and A-Z";
    }
    return null;
  }

  String validateMobile(String value) {
    String pattern = r'(^[0-9]*$)';
    RegExp regExp = new RegExp(pattern);
    if (value.length == 0) {
      return "Mobile is Required";
    } else if (value.length != 10) {
      return "Mobile number must 10 digits";
    } else if (!regExp.hasMatch(value)) {
      return "Mobile Number must be digits";
    }
    return null;
  }

  String validatePasswordLength(String value){
    if(value.length==0){
      return "Password can't be empty";
    } else if (value.length < 10){
      return "Password must be longer than 10 characters";
    }
    return null;
  }

  String validateEmail(String value) {
    String pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = new RegExp(pattern);
    if (value.length == 0) {
      return "Email is Required";
    } else if (!regExp.hasMatch(value)) {
      return "Invalid Email";
    } else {
      return null;
    }
  }
}

Here is some of my signin.dart code where i got an error.

Widget form() {
    return Container(
      margin: EdgeInsets.only(
          left: _width / 12.0, right: _width / 12.0, top: _height / 15.0),
      child: Form(
        key: _key,
        autovalidate: _validate,
        child: Column(
          children: <Widget>[
            emailTextFormField(),
            SizedBox(height: _height / 40.0),
            passwordTextFormField(),
          ],
        ),
      ),
    );
  }
   Widget emailTextFormField() {
    return CustomTextField(
      keyboardType: TextInputType.emailAddress,
      textEditingController: emailController,
      icon: Icons.email,
      hint: "Email ID",    
      validator: Validator().validateEmail,
    );
  }

  Widget passwordTextFormField() {
    return CustomTextField(
      keyboardType: TextInputType.emailAddress,
      textEditingController: passwordController,
      icon: Icons.lock,
      obscureText: true,
      hint: "Password",
    );
  }  

I try to called the Validator().validateEmail, to validate my text in emailTextFormField using “ validator: Validator().validateEmail,

It always show error : the argument type ‘String’ cant be assigned to parameter type Validator Any suggest to call the validator to validate the emailTextFormField using my Validator class?

Upvotes: 0

Views: 1375

Answers (2)

Simon Lemcke
Simon Lemcke

Reputation: 13

It has been over a year now, so you probably don't need any help anymore. Anyways: I just stumbled over this post with a similar problem.

Solution:

  • the attribute "validator" in the TextFormField asks for the name of a String Function -> therefore you don't have to use () to tell it that it's a function
  • if you delete the validator class wrap and just leave the functions it'll work fine:

Something like this:

validate.dart:

String validateName(String value) {
    String pattern = r'(^[a-zA-Z ]*$)';
    RegExp regExp = new RegExp(pattern);
    if (value.length == 0) {
      return "Name is Required";
    } else if (!regExp.hasMatch(value)) {
      return "Name must be a-z and A-Z";
    }
    return null;
  }

main.dart:

import 'validate.dart';

(...)
    
return CustomTextField(
      validator: validateName,
    (...)
    );

Hope that helps someone at some point :)

Upvotes: 0

SaravanaRaja
SaravanaRaja

Reputation: 3406

Change this line in the CustomTextField

class CustomTextField extends StatelessWidget {

//final Validator validator;//remove this line
final FormFieldValidator<String> validator; // add this line

Upvotes: 2

Related Questions