簡體   English   中英

React Native:如何在提交時驗證用戶名和密碼

[英]React native: How to validate username and password while submitting

我已經驗證了用戶名和密碼,如果用戶名和密碼錯誤,那么我想通過“無效的用戶名/密碼”之類的錯誤信息。如果有人知道,請告訴我。

 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);
        } 
      }
    }

輸入無效的用戶名/密碼后的響應:

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

我已經根據身份驗證過的用戶名/密碼寫了這樣的代碼,正確/錯誤。因此,這里發布代碼是否對將來的任何人有用。下面的代碼是,

 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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM