简体   繁体   中英

React native: How to validate username and password while submitting

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.

 async submit() {        
      //Validating username and password
       const { username, password } = this.state;
       if(username == ''){
          this.setState({error:'Username is required'});
       } else if(password == ''){
          this.setState({error:'Password is required'});
       } else {     
        this.setState({error: null})  
        let collection={};
        collection.username=this.state.username;
        collection.password=this.state.password;
        // console.warn(collection);

        var url = 'my url';
          try {
            let response = await fetch(url, 
            {
              method: 'POST', // or 'PUT'
              body: JSON.stringify(collection), // data can be `string` or {object}!
              headers: new Headers({
                'Content-Type': 'application/json'
              })
            });
            let res = await response.text();
          // console.warn(res);

          if (response.status >= 200 && response.status < 300) { 
            //Handle success
            let accessToken = res;
            console.log(accessToken);
            //On success we will store the access_token in the AsyncStorage
            this.storeToken(accessToken);
            // console.warn(accessToken);
            //After storing value,it will navigate to home 
            this.props.navigation.navigate('Home');

          } else {
            //Handle error
            console.log('Success:',response);
            let error = res;
            throw error;
          }
        } catch(error) { 
            console.log("error " + error);
        } 
      }
    }

response after giving invalid username/password:

0   {…}
field   :password
message :Incorrect username or password.

I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,

 if (response.status >= 200 && response.status < 300) { 
       //Handle success

       let accessToken = res;
       //On success we will store the access_token in the AsyncStorage
       this.storeToken(accessToken);
       console.warn(accessToken);
       //After storing value,it will navigate to home 
       this.props.navigation.navigate('Home'); 

    } else {
       console.log('Success:',response);
       this.setState({error:'Invalid username/password'});
       let error = res;
       throw error;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM