Coder Social home page Coder Social logo

react-native-form-validator's People

Contributors

angryr4v3n avatar arochedy avatar aymanhossam avatar dependabot[bot] avatar dharnarh avatar diariolibre avatar fcostaprojects avatar heyman333 avatar imamsutono avatar lahmacun avatar mahinsagotra avatar mahmoudaliibrahim avatar perscrew avatar phoenix-gh avatar rennanribeiro avatar reyalpsirc avatar robertplant avatar shikhar91939 avatar tdervilyiad avatar tesmor avatar thg303 avatar vitorluizc avatar wodka avatar xavierolland avatar yotapr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-form-validator's Issues

Dynamic rule validation require

Hi @perscrew, how to use dynamic rule validation:
Example:

values = { name: 'test', date: '', checkDate: false }
const validForm = this.validate({
      name: { required: !checkDate },
      date: { required: checkDate }
})

=> validForm = false

On validate, the variable name is pass ok, but variable date is require: false, bypass false value.

the variable checkDate is dynamic with Switch component in react native screen

validate nested state

Hi,
I want to know how can I validate nested object in state with react-native-form-validator?
for example I have a state like this:
state = { loading: false, controls: { cellPhone: { value: "", touched: false }, userName: { value: "", touched: false } } }
How can I validate cellPhone.value, userName.value?

Skipping not required fields validation if the field is empty

I fixed _checkRules function a little bit - if the field is empty and not required there should be no errors, for example that email is not valid or something else

// Method to check rules on a spefific field
  _checkRules(fieldName, rules, value) {
    + const isRequired = !!rules.required;
    + if (!isRequired && !value.length) {
    +  //Nothing to check
    +  return;
    +}
    for (const key of Object.keys(rules)) {
      const isRuleFn = (typeof this.rules[key] == "function");
      const isRegExp = (this.rules[key] instanceof RegExp);
      if ((isRuleFn && !this.rules[key](rules[key], value)) || (isRegExp && !this.rules[key].test(value))) {
        this._addError(fieldName, key, rules[key], isRuleFn);
      }
    }
  }

A new version with equalPassword

I installed the latest version 0.3.2 using npm install but it doesn't have the equalPassword in defaultRules.js.
Can you help me?

isFieldInError and getErrorsInField doesn't work and custom messages

Hello, I'm trying to make conditionals with isFieldInError and getErrorsInField, but it returned me false and an empty array respectively even having errors, this is my code, I'm doing like a reusable component.

function RegisterForm({data}) {
  const [field, setField] = useState('');
  const [value] = useDebounce(field, 1000);

  const {validate, isFieldInError, getErrorsInField, getErrorMessages} =
    useValidation({
      state: {field},
    });

  const _validateForm = () => {
    validate({
      field: data.rules,
    });
  };

  React.useEffect(() => {
    if (value.length !== 0) {
      _validateForm();
    }
  }, [value]);

  return (
    <View style={tailwind('px-8')}>
      <TextInput
        placeholder={data.placeholder}
        style={[
          tailwind('text-black p-0 text-xl pb-1 flex-row'),
          {
            borderBottomWidth: 1,
            borderBottomColor: '#808080',
          },
        ]}
        onChangeText={text => setField(text)}
        value={field}
      />
      <Text>{getErrorMessages()}</Text>
      <TouchableOpacity onPress={() => _validateForm()}>
        <Text>auwhdauywd</Text>
      </TouchableOpacity>
    </View>
  );
}

And I want to use custom messages but I don't know how, please help me, thank you

how to not expose state variable names?

Is there a way to not expose the state variable names?
Example:
this.state = { firstName: '' }

If it´s required, the default error would be 'The field "firstName" is mandatory.', right?

I´d like to set to something like 'The field "first name" is mandatory.'

Is it possible?

Validation passes for single character string; need to type two characters before `getErrorsInField` returns error messages

Hi guys!

I have the following React context provider:

import React, { useState, useEffect, createContext } from 'react';

import auth from '@react-native-firebase/auth';
import { useValidation } from 'react-native-form-validator';

import { validationMsgs, validationRules } from './auth.validation';
import { ErrorText } from '../../features/auth/components/auth.styles';

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
    const [ currentUser, setCurrentUser ] = useState(null);
    const [ passResetCode, setPassResetCode ] = useState('');

    const [ isLoading, setIsLoading ] = useState(false);
    const [ error, setError ] = useState(null);

    const [ displayName, setDisplayName ] = useState('');
    const [ emailAddress, setEmailAddress ] = useState('');

    const [ password, setPassword ] = useState('');
    const [ passwordMatch, setPasswordMatch ] = useState('');

    const { validate, getErrorsInField, isFormValid } =
        useValidation({
            state: {
                displayName,
                emailAddress,
                password,
                passwordMatch,
            },
            messages: validationMsgs,
        });

    const onLoginUser = async (email: string, pass: string) => {
        setIsLoading(true);

        try {
            await auth().signInWithEmailAndPassword(email, pass);
        } catch (e: any) {
            setError(e.toString());
        } finally {
            setIsLoading(false);
        }
    };

    // ...many other wrappers around various Firebase Auth functions, such as createUserWithEmailAndPassword

    const validateField = (field, numLines) => {
        const rules = {};
        rules[field] = validationRules[field];

        const isValid = validate(rules);

        return isValid ? null : getErrorsInField(field).map((e, i) => (
            <ErrorText key={i} numberOfLines={numLines}>
                {e.replace(/[A-Z]/g, letter => ` ${letter.toLowerCase()}`)
                    .replace(/^[a-z]/, letter => `${letter.toUpperCase()}`)}
            </ErrorText>
        ));
    };

    useEffect(() => {
        return auth().onAuthStateChanged(user => {
            if (user) {
                setCurrentUser(user);
            }
            setIsLoading(false);
        });
    }, []);

    return (
        <AuthContext.Provider
            value={{
                isAuthenticated: !!currentUser,
                currentUser,
                displayName,
                emailAddress,
                isLoading,
                error,
                password,
                passwordMatch,
                isFormValid,
                onLoginUser,
                onRegisterUser,
                onLogoutUser,
                onSendResetEmail,
                onResetPassword,
                setDisplayName,
                setEmailAddress,
                setError,
                setPassword,
                setPasswordMatch,
                validateField,
            }}>
            {children}
        </AuthContext.Provider>
    );
};

And the following consumer of this context:

import React, { useContext, useState } from 'react';
import { ScrollView } from 'react-native';
import { ActivityIndicator, Button, Colors, TextInput } from 'react-native-paper';

import { AuthContext } from '../../../services/auth/auth.context';
import { ErrorText } from '../components/auth.styles';
import { StyledText } from '../../../components/typography/text.component';

export const LoginScreen = ({ navigation }) => {
    const { emailAddress, error, isLoading, isFormValid, onLoginUser,
        password, setEmailAddress, setPassword, validateField,
    } = useContext(AuthContext);

    const [ fieldErrors, setFieldErrors ] = useState({});

    const onSubmit = () => {
        if (isFormValid()) {
            onLoginUser(emailAddress, password);
        }
    };

    return (
        <StyledText fontSize="h5" marginTop={'55%'} marginBottom="16px">
            Meals 2 U
        </StyledText>
        <ScrollView>
            <TextInput
                label="Email address"
                value={emailAddress}
                textContentType="emailAddress"
                keyboardType="email-address"
                autoCapitalize="none"
                onChangeText={e => {
                    setEmailAddress(e);
                    setFieldErrors({ ...fieldErrors, emailAddress:
                        validateField('emailAddress', 2) });
                }} />
            {fieldErrors.emailAddress}
            <TextInput
                label="Password"
                value={password}
                textContentType="password"
                secureTextEntry
                autoCapitalize="none"
                onChangeText={p => {
                    setPassword(p);
                    setFieldErrors({ ...fieldErrors, password:
                        validateField('password', 6) });
                }} />
            {fieldErrors.password}
            {error && (
                <ErrorText numberOfLines={3}>{error}</ErrorText>
            )}
            {isLoading ? (
                <ActivityIndicator
                    animating={true}
                    color={Colors.blue300}
                />
            ) : (
                <>
                    <Button
                        icon="lock-open-outline"
                        mode="contained"
                        onPress={() => onSubmit()}
                        disabled={!emailAddress || !password || !isFormValid()}>
                        Login
                    </Button>
                    <Button
                        icon="account-plus"
                        mode="contained"
                        onPress={() => {
                            setEmailAddress('');
                            setPassword('');
                            navigation.navigate('Register');
                        }}>
                        Register
                    </Button>
                    <Button
                        icon="lock-reset"
                        isLastButton={true}
                        mode="contained"
                        onPress={() => {
                            setEmailAddress('');
                            setPassword('');
                            navigation.navigate('Reset Password');
                        }}>
                        Reset Password
                    </Button>
                </>
            )}
        </ScrollView>
    );
};

This all works great, except that I have to enter two characters into either of the TextInputs before getErrorsInField actually returns any error messages.

Stepping through the code I can see that the validate function is returning false straight away (i.e. after typing a single character), but this has no effect on getErrorsInField until another character is typed.

Is this intended behaviour? If so, why?! It seems to me as though anyone would expect errors to be returned immediately!

In any case, how can I fix this behaviour? MTIA 😄.

Confirm Password check

Hello,

I have 2 fields, password and confirm password. I would like to know how to perform this validation, to compare the value of confirm password with that of the password field?

this.validate not working onPress button, only onChangeText input

I have this.validate({...}) method inside an onPress function, but this.validate is not fired when I press the button, this.validate is only fired when I write in the inputs. So this.getErrorMessages() is not returning nothing when I trigger onPress event, but it does return a response when I write in inputs.

¿Should it work like that?

NOTE: I'm working with nativebase.

  • Constructor
constructor() {
   super();
   this.state = { email: '' }
}
  • onPress function
login = () => {
    this.validate({
      email : {required: true, email: true}
    });
  }
  • Input component
   <Input style={styles.input}
      value={this.state.email}
      keyboardType='email-address'
      ref={(ref) => this.email = ref}
     onChangeText={(email) => this.setState({email})}
   />
  • Button and error messages Text
<Text>{this.getErrorMessages()}</Text>

<Button onPress={() => this.login()}>
   <Text>LOGIN</Text>
</Button>

Validate array of object

Hi this validation library is so easy to use, thank you for your effort.
Now I am looking for example of validation for array of object, but not found.

How to use this validation to validate array of object?
For example I have data array of users, how to validate it?

Thank you.

Please add License Text

Please add License to this repository .Due to strict Open source standards it will be helpful if you can add License

Package has stopped working entirely since moving my project to TypeScript

Hi guys!

I posted another issue almost a day ago re: getErrorsInField not returning errors for a single character input, and now my problems seem to be getting worse.

I have since migrated my project across to TypeScript in the hope that strict type checking would help me solve this and a few other (unrelated to this package) errors that I'm getting. Well I don't know whether that's the culprit or not, but now getErrorsInField returns [] regardless of the amount of characters in the validated input (i.e. the whole package has become useless)!

I've been looking into this on my own since I haven't heard from anyone in almost a day, and I need this to have been fixed yesterday, not some time in the distant future. Please don't take that comment as an aggressive one; I understand that we all get busy and replying to whining users is probably at the bottom of everyone's to-do list 😉.

Anyway, I just noticed something strange in the code:

errors.current.push({
fieldName,
failedRules: [rule],
messages: [errMsg]
});
setInternalErrors(errors.current);

I don't understand the use of two variables to track the errors that have been caught. Sure, errors is a ref while internalErrors is a state variable, so that is an obvious difference between them. But I guess I don't understand React well enough to understand why this would be needed. Nor have I ever seen any other examples of this type of design pattern in a React [Native] package.

Anyway, from what limited knowledge/experience I do have, it seems as though this is the cause of the errors I'm getting. Setting a debug breakpoint on line 81 and triggering it to be hit, I can see that errors.current is set to the expected array of 1 error object. But if I then hit F10 to step over that line, I end up with internalErrors still being set to an empty array!

Why is this occurring?? Could it have something to do with my TypeScript type definitions being wrong somehow?

Futhermore, if I continue stepping through the code until reaching the following:

const isFormValid = () => {
return errors.current?.length == 0;
};

It becomes even more apparent (to me at least) that you guys should just use the errors ref variable, and get rid of the seemingly-useless internalErrors state variable. That isFormValid function returns false just like it should, but getErrorsInField relies solely on the incorrect state variable, meaning that validate returns false but getErrorsInField returns []!

I hope that this is a helpful bug report that solves a lot of problems for a lot of future users. I may even use Patch Package to fix this bug and submit a PR to you guys if you're interested 😉.

Custom Rules

Hello, I'm trying to add a custom validation rule to validate CPF that is a document in Brazil, but it is not working. Does anyone know how to do?

Regex Used: / (^ \ d {3} . \ D {3} . \ D {3} \ - \ d {2} $) | (^ \ d {2} . \ D {3} \ . \ d {3} \ / \ d {4} \ - \ d {2} $) /

constructor(props) {
    super(props);
    this.deviceLocale = "ptBR"
    this.state = {
        cpf: '',
        nome: '',
        email: ''
    };
    this.messages = {
        ptBR: {
            required: 'O campo é obrigatório.',
            email: 'O campo "{0}" precisa conter um email válido.',
            cpf: 'O campo "{0}" precisa conter um CPF válido.',
        }
    };

    this.defaultRules = {
        cpf: /(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)|(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/,
    };
}

Undefined is not an object (evaluating '_react.PropTypes.string')

Hi @perscrew

I followed the documentation from the readme file.
This is the error I got: Undefined is not an object (evaluating '_react.PropTypes.string').

Do you have any idea what's going on here?
I suppose that this package imports PropTypes from react and not from prop-types.

I use react-native v0.48.3 and react v16.0.0-beta.5

Thanks

this.validate is undefined

Hello i have just started using this. However i cann't perform simple validation
simulator screen shot - iphone 7 - 2017-11-04 at 16 48 34

I have extended from ValidationComponent. Any idea what i might be doing wrong

export default class LoginComponent extends ValidationComponent {

    static navigationOptions = { title: 'Login Screen' };

    constructor(props) {
        super(props);

        this.state = {
            userName: '',
            password: '',
            // navigation :this.props.navigation,
        };

 loginTapped() {
        this.validate({
            userName: { required: true },
            password: { email: true }
        });

this.validate is not a function" in TypeError: this.validate is not a function << at ...

Perhaps I'm not getting something, nothing in this package seems to work at all.

this.validate is not a function" in TypeError: this.validate is not a function << at _onSubmit
  _onSubmit() {
      this.validate({
        emailField: {email: true, required: true},
        passwordField: {required: true}
      });
  }
...
          <TextInput
            ref="emailField"   deviceLocale="fr"
            style={AppStyles.input}
            keyboardType="email-address"
            placeholder="Email Address"
            onChangeText={(emailField) => this.setState({emailField})} value={this.state.emailField} 
          />

use with redux

Hi,
Is it possible to use react-native-form-validator with redux, this.pops... instead of state?

this.isFormValid is always true.

When i console.log(this.isFormValid);
Result :
ƒ isFormValid() {
return this.errors.length == 0;
}

`import ValidationComponent from 'react-native-form-validator';

export default class extends ValidationComponent {
constructor(props) {
}

// onPress of the Submit button I am invoking this function to validate all my fields.
submitCredentials = () => {

    // TODO : Get the Location details 
    // TODO : Validate the type of data in the Regsiter Form 
    // TODO : 
    console.log("Validating the Form"); 
    this.validate({
        _password   : {required: true},
        _email      : {email: true},   // Sample: I am entering the "sdfjhsbdjfh" in the email field
        _name       : {required: true},
        _lastname   : {required: true},
        _phone      : {numbers: true}, 
        _alias_name : {required: true},
        _isd        : {required: true},
    })
    console.log(this.isFormValid); // returns the function on console
    if(this.isFormValid){   // Always true even if incorrect data is entered in form. 
        this.fireRegisterAPI();
    }

}`

Please help with the solution. What am I missing here? Any setup issue?
TIA

Undefined is not a function (evaluating 'this.validate')

I got error in _onPressButton, it refers to :
_onPressButton() {
// Call ValidationComponent validate method
this.validate({
userEmail: {email: true, minlength:6, required: true},
userPassword: {minlength:6, required: true}
}).then(Actions.index());
}

How to focus in validation field on submit

I have a form with more than 10 fields, suppose my first field of form is required. when I go to bottom of the form without entering any value in required fields and click of submit button, I want to set auto cursor on the required field on submit click.

No Spanish defaultMessages

In the Documentation, spanish device locale is define but the current version of the library does not support 'es.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.