天天看點

微信小程式 picker選擇器 表單驗證 源碼

微信小程式表單驗證(這是自己寫的,比較low,下篇附上公司大佬的源碼,嘿嘿)

所在城市帶選擇城市的功能

比較懶笨,附上的代碼是完整的,把接口資料換成自己的就可以用了,樣式需要自己調,請在評論區誇我 !!!

微信小程式 picker選擇器 表單驗證 源碼
微信小程式 picker選擇器 表單驗證 源碼

附上要用的API的路徑  https://developers.weixin.qq.com/miniprogram/dev/component/picker.html?search-key=picker

微信小程式 picker選擇器 表單驗證 源碼

附上的源碼功能比較多,比較混亂

功能:所在城市不能手寫,要從背景伺服器拿到資料選擇城市,當選中城市時,選中的值替換掉input中的值

思路:這裡主要使用picker選擇器,

1.在js中定義index2,初始值為空,

data: { index2: '',//城市下标 },

2.當選中的城市改變時,觸發bindPickerzone事件,value的值也随之變化,

   此時需要在bindPickerzone事件中把新的value值賦給index2,

//所在城市選擇

bindPickerzone: function (e) {

     console.log('picker發送選擇改變,攜帶值為', e.detail.value)

     this.setData({

         index2: e.detail.value

     })

},

3.傳回前端input框,将拿到的下标對應的元素值顯示出來即可

<picker bindchange="bindPickerzone" value="{{index2}}" range="{{userZoneList}}">

    <input class='fl' type='text' placeholder='所在城市' placeholder-class='place' name="city" disabled='disabled'                                value='{{userZoneList[index2]}}'></input>

    <text class='fr m_t5 grayb'style='margin-right:20rpx;'>﹀</text>

    <view class='cl'></view>

</picker>

小程式前端布局

<!--pages/activity/signup/signup.wxml-->
<!-- banner圖 -->
<view class='bg_white' style='padding-bottom:30rpx;'>
  <image src='/images/actbanner.jpg' style='width:100%;height:220rpx;'></image>
</view>
<!-- 表單主要内容 -->
<view class='p_b20' style='width:90%;margin:0 auto;'>
  <form bindsubmit="formSubmit">
    <view class='addview20' style='padding-bottom:90rpx;'>
      <view class='bg_white font14 gray5 p_all10 p_b20'style='width:95%;margin 0 auto;padding-top:20rpx;'>
        <view class='inputstyle'>
          <picker bindchange="bindPickerzone" value="{{index2}}" range="{{userZoneList}}">
            <input class='fl' type='text' placeholder='所在城市' placeholder-class='place' name="city" disabled='disabled' value='{{userZoneList[index2]}}'></input>
            <text class='fr m_t5 grayb'style='margin-right:20rpx;'>﹀</text>
            <view class='cl'></view>
          </picker>
        </view>
        <input type='number' class='inputstyle' placeholder-class='place' name="area" placeholder='房屋面積(㎡)'></input>
        <input type='number' class='inputstyle' maxlength='11' placeholder-class='place' name="phoneNumber" placeholder='手機号'></input>
        <input type='text' class='inputstyle' placeholder-class='place' name="userName" placeholder='姓名'></input>
      </view>
      <!-- 正文内容 -->
      <view class='p_lr15' wx:if="{{content.length > 0}}">
        <view class='contentView' wx:for="{{content}}">
          <view class='m_t30 pr' wx:if="{{item.name == 'img'}}">
            <image src='{{item.contents}}' mode='widthFix' style='width:100%;'></image>
            <view class='delet pa tc font22 white bg_grayc' data-index='{{index}}' bindtap='deletTap'><text>×</text></view>
          </view>
          <view class='font15 gray2 tj lineH_m text p_all10 m_t30 pr' wx:if="{{item.name == 'text'}}">
            <text>{{item.contents}}</text>
            <view class='delet pa font22 white bg_grayc' data-index='{{index}}' bindtap='deletTap'><text>×</text></view>
            <view class='edit pa bg_grayc tc' data-index='{{index}}' bindtap='editTap'>
              <image src='/images/icon/edit.png' style='width:26rpx;height:26rpx;margin-top:12rpx'></image>
            </view>
          </view>
        </view>
      </view>
    
      <view class='tc p_tb15'>
        <text class='block font15 gray9' wx:if="{{content.length <= 0}}">開始添加内容</text>
        <view class='m_t10' bindtap='addTap'><text class='addto bg_graye white font24' bindtap='addtoTap'>+</text></view>
        <view class='inline_block p_tb5 p_lr30 addview m_t10' wx:if="{{addHidden == false}}">
          <view class='inline_block m_r20' bindtap='addTextTap'>
            <image src='/images/icon/fa_03.png' style='width:40rpx;height:40rpx;'></image>
            <text class='block font14 gray2 tc'>文字</text>
          </view>
          <view class='inline_block' bindtap='chooseImg'>
            <image src='/images/icon/fa_05.png' style='width:40rpx;height:40rpx;'></image>
            <text class='block font14 gray2 tc'>圖檔</text>
          </view>
        </view>
      </view>
    
      <view class='pf textrea bg_white {{textreaHidden == true ? "animation_huachu" : "animation_huaru"}}' wx:if="{{textreaHidden == false}}">
        <form bindsubmit="textreaSubmit">
          <view class='p_all15 bd_b'style='min-height:300rpx;'>
            <textarea value='{{editVal}}' adjust-position="true" maxlength='-1' name="textarea" placeholder='請輸入内容……' auto-height='true' class='font15 gray2'></textarea>
          </view>
            <view class='tr p_lr15'>
              <button class='green font16' form-type="submit">
                <text>完成</text>
              </button>
            </view>
        </form>
      </view>
    </view>
  <!-- 送出報名 -->
    <view class='tr p_lr15 bg_white' style='margin-top:30rpx;'>
      <button class='form_button' form-type="submit">
        <text class='p_tb5 p_lr20 bg_theme white font16 tc block' style='border-radius:15rpx;width:100%;height:80rpx;line-height:60rpx;margin: 0 auto;'>送出資訊</text>
      </button>
    </view>
  </form>
</view>


           

js

// pages/forum/publish/publish.js
//擷取應用執行個體
const app = getApp()
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    sortCurrent: '',//
    upload_limit: 1,// 預設最多上傳9張
    img_srcs: [], //如果是編輯狀态,隻需要把原資訊的圖檔位址放到此處就可以顯示出來
    img_src: [],
    content: [],//正文内容
    textreaHidden: true,
    addHidden: false,
    editVal: '',//編輯文字内容
    editIndex: '',//編輯的index
    userZoneList: [],//城市清單
    index2: '',//城市下标
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    var that = this;
    //wx.hideShareMenu();//隐藏分享
    //顯示頂部加載動畫
    wx.showNavigationBarLoading(
      console.log('頁面加載開始'),
    );  
    wx.request({
      url: app.d.hostUrl + 'home.articleType',
      method: 'GET',
      header: {
        'Accept': 'application/json'
      },
      success: function (res) {
       // console.log(res)
        var data = res.data;
        that.setData({
          sortCurrent: data[0].id,
        })
       }
    })
    //城市清單
    wx.request({
      url: app.d.ceshiUrl + 'activity.areaList',
      success: function (res) {
        console.log(res.data)
        var res = res.data;
        that.setData({
          userZoneList: res,
        })
        wx.hideNavigationBarLoading();
      }
    })
  },

  //所在城市選擇
  bindPickerzone: function (e) {
    console.log('picker發送選擇改變,攜帶值為', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },

  articlecurrentTap: function (e) {
    var that = this;
    console.log(e);
    that.setData({
      sortCurrent: e.target.id,
    })
  },
  addTap: function (e) {
    var that = this;
    if (that.data.addHidden == false) {
      that.setData({
        addHidden: true,
        editIndex: '',
        editVal: '',
      })
    } else {
      that.setData({
        addHidden: false,
        editIndex: '',
        editVal: '',
      })
    }
  },
  //上傳圖檔
  chooseImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: that.data.upload_limit,
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,預設二者都有
      success: function (res) {
        // 傳回標明照片的本地檔案路徑清單,tempFilePath可以作為img标簽的src屬性顯示圖檔
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        that.sendPhotos(tempFilePaths);
        console.log(that.data.content);
      }
    })
  },
  //發圖檔發送給後端伺服器
  sendPhotos: function (tempFilePaths) {
    var that = this
    wx.showNavigationBarLoading();
    console.log(tempFilePaths[0])
    if (tempFilePaths.length !== 0) {
      wx.uploadFile({
        url: app.d.ceshiUrl + 'comment.uploadPic',
        filePath: tempFilePaths[0],
        name: 'picture',
        header: { "Content-Type": "multipart/form-data" },
        success: function (res) {
          console.log(res.data)
          var data = JSON.parse(res.data)
          console.log(data)
          var j = that.data.content.length;
          var content = that.data.content;
          if (data !== '') {
            var path = data.path;
            content[j] = {
              "name": "img",
              "contents": "https://xcx.fczxwl.com/attachment/" + path
            };
          }

          that.setData({
            content: content,
            addHidden: true
          });
          console.log(that.data.content)
          wx.hideNavigationBarLoading();
          tempFilePaths.splice(0, 1);
          
          // that.sendPhotos(tempFilePaths);
        },
        fail: function (res) {
          console.log('上傳圖檔到伺服器失敗');
        },
        complete: function (res) {
          console.log(res);
        }
      })
    }
  },
  //圖檔預覽
  previewImage: function (e) {
    var img_srcs = this.data.img_srcs;
    var index = e.target.dataset.index;
    wx.previewImage({
      current: img_srcs[index],
      urls: img_srcs           // 需要預覽的圖檔http連結清單
    })
  },
  //删除内容快
  deletTap: function (e) {
    var that = this;
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var content = that.data.content;
    wx.showModal({
      title: '提示',
      content: '确定要删除?',
      success: function (res) {
        if (res.confirm) {
          content.splice(index, 1)
          that.setData({
            content: content,
          })
        }
      }
    })
  },
  addTextTap: function (e) {
    var that = this;
    that.setData({
      textreaHidden: false,
    })
  },
  //文字textrea送出
  textreaSubmit: function (e) {
    var that = this;
    console.log(e.detail.value.textarea)
    var j = that.data.content.length;
    var content = that.data.content;
    var value = e.detail.value.textarea;
    console.log(value);//上傳的内容
    //判斷内容是否為空
    if (value !== "") {
      if (that.data.editIndex !== '') {
        //editIndex
        content[that.data.editIndex].contents = value;
      } else {
        content[j] = {
          "name": "text",
          "contents": value
        };
      }
      that.setData({
        textreaHidden: true,
        content: content,
        addHidden: true
      })
      console.log(that.data.content)
    } else {
      wx.showModal({
        title: '提示',
        content: '内容不能為空,請輸入内容',
        success: function (res) {
          if (res.confirm) {
            return false;
          } else {
            that.setData({
              textreaHidden: true,
            })
          }
        }
      })
    }
  },
  //文字編輯
  editTap: function (e) {
    var that = this;
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var content = that.data.content;
    that.setData({
      textreaHidden: false,
      editVal: content[index].contents,
      editIndex: index,
    })
  },

  //釋出送出資訊
  formSubmit: function (e) {
    wx.showNavigationBarLoading();
    var userInfo = wx.getStorageSync('userInfo');//使用者基本資訊
    var that = this;
    console.log(that.data.content);
    //console.log(e)
    var city = e.detail.value.city;//所在城市
    var area = e.detail.value.area;//房屋面積
    var phoneNumber = e.detail.value.phoneNumber;//手機号
    var userName = e.detail.value.userName;//姓名
    console.log(e.detail.value)
    var arr = {//正文内容
      "content": that.data.content
    }
    var typeid = that.data.sortCurrent;
    var typename;
    var mobile = /^[1][3,4,5,7,8][0-9]{9}$/;
    var isMobile = mobile.exec(e.detail.value.phoneNumber)
    //所有消息有任一為空時
    if (city == "" || area=="" || phoneNumber=="" || userName=="") {
      wx.showModal({
        title: '釋出提示',
        content: '您的資訊缺失,請重新填寫!',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            return false;
          }
        }
      })
      wx.hideNavigationBarLoading();
    }
    //判斷電話号格式是否正确
    else if (!isMobile) {
      console.log('form表單發生點選事件,攜帶的資料為:', e.detail.value)
      console.log('電話:', e.detail.value.phoneNumber)
        wx.showModal({
          title: '提示!!',
          content: '你輸入的電話不符,請重新檢查填寫',
         })
    }
    //當所有消息不為空
    else {
      //判斷主要内容
      console.log(arr.content.length);
      if (arr.content.length == 0){
        wx.showModal({
          title: '釋出提示',
          content: '文章内容不能為空,請編輯内容',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              return false;
            }
          }
        })
        wx.hideNavigationBarLoading();
      }else{
        wx.request({
          url: app.d.hostUrl + 'activity.addApply',
          data: {
            "openid": wx.getStorageSync('openid'),
            "nickname": userInfo.nickName,   //昵稱
            "avatar": userInfo.avatarUrl,  //頭像
            // "title": title,
            "name": e.detail.value.userName,  //姓名
            "zone": e.detail.value.city,   //城市
            "area": e.detail.value.area,   //手機号
            "tel": e.detail.value.phoneNumber,   //手機号
            "content": arr,  //内容
          },
          method: 'GET',
          header: {
            'Accept': 'application/json'
          },
          success: function (res) {
            console.log(res)
            wx.hideNavigationBarLoading();
            wx.showToast({
              title: '已送出報名',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.reLaunch({
                    url: '/pages/activity/home/home',
                  })
                }, 2000)
              }
            })
          }
        })
      }
    }
  },
  /**
   * 生命周期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命周期函數--監聽頁面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函數--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === "button") {
      console.log("來自頁面内轉發按鈕");
      console.log(res.target);
    } else {
      console.log("來自右上角轉發菜單")
    }
    return {
      title: '嘿,裝修',
      path: '/pages/index/index?shareid=' + wx.getStorageSync("openid"),
      success: (res) => {
        console.log("轉發成功", res);
      },
      fail: (res) => {
        console.log("轉發失敗", res);
      }
    }

  }
})
           

補充的有代表性的樣式

.addview20{
  border-radius: 40rpx;
  box-shadow: #aaa 0px 1px 5px;
}

.inputstyle{
  width: 90%;
  height: 60rpx;
  border-radius:15rpx;
  padding: 15rpx 0 15rpx 55rpx;
  background-color: #eee;
  margin-top:30rpx;
  margin-left:20rpx;
  font-size: 28rpx;
}

.contentView .text{
  box-shadow: #bbb 0px 1px 5px;
  border-radius: 10rpx;
}
.contentView .delet{
  width: 50rpx;
  height: 50rpx;
  line-height: 50rpx;
  top: -30rpx;
  right: 20rpx;
  border-radius: 50%;
  z-index: 9;
}
.contentView .delet text{
  display: block;
  text-align: center;
  margin: auto;
}
.contentView .edit{
  width: 50rpx;
  height: 50rpx;
  top: -30rpx;
  right: 90rpx;
  border-radius: 50%;
  z-index: 9;
}

.inline_block{display: inline-block;}

.textrea{
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 99;
}

.textrea button{
  display: inline-block;
  background: none;
  border: 0;
  margin: 0;
  padding: 0;
  padding-left:0;
  padding-right:0;
  border-radius:0;
}
.textrea button::after{
  content:'';
  width:0;
  height:0;
  -webkit-transform:scale(1);
  transform:scale(1);
  display:none;
  background-color:transparent;
}

.pf{position: fixed;}