Home > Back-end >  Why is validation not working as intended?
Why is validation not working as intended?

Time:10-16

I have a signUpUser Future in a Auth class that somewhat validates user details onSubmit and the function validates email and password but still submits when the user doesn't enter a username or bio. I receive: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast but the user is still logged in.

    Future<String> signupUser({
    required String email,
    required String password,
    required String username,
    required String bio,
    required Uint8List file,
  }) async {
    String res = 'Some error occurred';
    try {
      if (email.isNotEmpty ||
          password.isNotEmpty ||
          username.isNotEmpty ||
          bio.isNotEmpty ||
          file != null) {
        //register user
        UserCredential cred = await _auth.createUserWithEmailAndPassword(
            email: email, password: password);

        print(cred.user!.uid);

        String imageUrl = await StorageMethods()
            .uploadImageToStorage('profileImages', file, false);

        // add user to database
        model.User user = model.User(
          email: email,
          username: username,
          uid: cred.user!.uid,
          imageUrl: imageUrl,
          bio: bio,
          followers: [],
          following: [],
        );
        await _firestore
            .collection('users')
            .doc(cred.user!.uid)
            .set(user.toJson());

        res = 'success';
      } else if (email.isEmpty && password.isEmpty) {
        res = 'Please enter email and password';
      } else if (email.isEmpty || password.isEmpty) {
        res = 'Please enter email and password';
      } else if (username.isEmpty) {
        res = 'Please enter username';
      } else if (bio.isEmpty) {
        res = 'Please enter bio';
      }
    } on FirebaseAuthException catch (err) {
      //print(err);

      if (err.code == 'invalid-email') {
        res = 'The email address is badly formatted';
      } else if (err.code == 'weak-password') {
        res = 'The password must be longer than 6 characters';
      } else if (err.code == 'email-already-in-use') {
        res = 'The email address already exists';
      } else {
        res = 'Please enter all fields';
      }
    } catch (err) {
      res = err.toString();
      print(res);
    }
    return res;
  }

I'm using a TextEditingController to save the text. Please let me know if I must add more code?

CodePudding user response:

You'll want to change your '||' clauses to '&&'. You currently have it writted to allow the user to try and register as long as they enter one of any of those fields. By placing a '&&' instead, it will require all of those fields to be entered before attempting to register.

  • Related