您的位置:首页 > 房产 > 家装 > vue中rules自定义规则实现

vue中rules自定义规则实现

2024/10/6 12:23:22 来源:https://blog.csdn.net/weixin_38225763/article/details/141062933  浏览:    关键词:vue中rules自定义规则实现

html代码

定义prop="shifandiqu"

            <el-col :span="24"><el-form-item label="平台示范地区" style="margin-bottom: 6px;" prop="shifandiqu"><el-select v-model="form.provinceid" filterable placeholder="请选择省/直辖市" :disabled="isDisabled" style="width: 28%; margin-right: 8px;" @change="provincechange(form.provinceid)"><el-option v-for="( item ) in provinceArr" :key="item.areaId" :label="item.areaName" :value="item.areaId"></el-option></el-select><el-select v-model="form.cityAreaId" filterable placeholder="请选择市" :disabled="isDisabled" style="width: 28%; margin-right: 8px;" @change="countychange(form.cityAreaId)"><el-option v-for="( item ) in countyArr" :key="item.areaId" :label="item.areaName" :value="item.areaId"></el-option></el-select><el-select v-model="form.areaId" filterable placeholder="请选择区县" :disabled="isDisabled" style="width: 28%; margin-right: 8px;"><el-option v-for="( item ) in regionArr" :key="item.areaId" :label="item.areaName" :value="item.areaId"></el-option></el-select><span v-show="!isDisabled" class="addKeywords" @click="addAreasFun">添加地区</span><!-- <div v-show="!isDisabled">示范地区为城市群,请<span class="clickhere" @click="centerDialogVisible = true">点击这里</span></div> --></el-form-item></el-col>

js代码

rules中定义shifandiqu的验证规则

shifandiqu: [{ required: true, validator: shifandiqu, trigger: 'blur' }],

自定义规则:

    const shifandiqu = (rule, value, callback) => {

      if (this.areasArr.length < 1 && this.selectedCityComplete.length < 1) {

        callback(new Error('请选择示范地区/城市群'))

      } else {

        callback()

      }

    }

完整js代码

<script>export default {data() {const kaifadanwei = (rule, value, callback) => {if (this.danweiNameArr.length < 1) {callback(new Error('请选择系统开发单位'))} else {callback()}}const fujian = (rule, value, callback) => {if (this.form.attachments.length < 1) {callback(new Error('请上传附件'))} else {callback()}}const shifandiqu = (rule, value, callback) => {if (this.areasArr.length < 1 && this.selectedCityComplete.length < 1) {callback(new Error('请选择示范地区/城市群'))} else {callback()}}return {tempRoute: {},tablabel: '应用示范系统添加',activeName: 'first',form: {name: '',systemType: 'Bs',systemUrl: '',demoVideo: '', // 演示视频systemIntroduction: '',isAdaptation1: '',pageResolution: '',provinceid: '',cityAreaId: '',areaId: '',browserType: '',hardwareEnvironment: '',contact: '',contactCellphone: '',attachments: [] // 上传文件列表},companyList: [], // 企业名称数组systemTypeFlag: false, // 不同系统类型isAdaptation1Flag: false, // 是否页面自适应rules: {name: [{ required: true, message: '平台名称不能为空', trigger: 'blur' }],systemUrl: [{ required: true, message: '平台网址不能为空', trigger: 'blur' }],// demoVideo: [{ required: false, message: '请上传演示视频', trigger: 'blur' }],systemIntroduction: [{ required: true, message: '平台简介不能为空', trigger: 'blur' }],// kaifadanwei: [{ required: true, message: '请选择系统开发单位', trigger: 'blur' }],kaifadanwei: [{ required: true, validator: kaifadanwei, trigger: 'blur' }],browserType: [{ required: true, message: '请选择最佳适配浏览器类型', trigger: 'blur' }],pageResolution0: [{ required: true, message: '请选择是否屏幕自适应', trigger: 'blur' }],pageResolution: [{ required: false, message: '请选择屏显比例', trigger: 'blur' }],hardwareEnvironment: [{ required: true, message: '请填写运行硬件环境', trigger: 'blur' }],// fujian: [{ required: true, message: '请上传附件', trigger: 'blur' }],fujian: [{ required: true, validator: fujian, trigger: 'blur' }],// shifandiqu: [{ required: true, message: '请选择示范地区/城市群', trigger: 'blur' }],shifandiqu: [{ required: true, validator: shifandiqu, trigger: 'blur' }],contact: [{ required: true, message: '请填写系统联系人', trigger: 'blur' }],contactCellphone: [{ required: true, message: '请填写联系人电话', trigger: 'blur' }]},isDisabled: false,jianchengArr: [], // 平台简称数组danweiArr: [], // 系统开发单位数组_iddanweiNameArr: [], // 系统开发单位数组_nametotalNum: 1, // 添加论文作者计数count: 1,pageResolutionArr: [], // 分辨率数组browserTypesArr: [], // 适配浏览器类型数组provinceArr: [], // 省countyArr: [], // 市regionArr: [], // 区areasArr: [], // 所选地区数组fileUrl: '', // 当前修改文件urlcenterDialogVisible: false, // 示范城市群弹窗cityGroupArr: [], // 城市群数组数据selectedCityGroup: [], // 已选城市群selectedCityComplete: [], // 选择城市群传值数组checkAll: false, // 全选isIndeterminate: false, // 用以表示 checkbox 的不确定状态,一般用于实现全选的效果AreaScopes: [] // 城市群上传用数组}},mounted() {// this.getAreasFun('', 1)this.getProvinceFun()this.getCityGroupFun()this.getResolutionTypesFun()this.getBrowserTypesFun()this.getCompanyNameFun()this.tempRoute = Object.assign({}, this.$route)if (this.$route.query.type === 'view') {this.isDisabled = truethis.$route.meta.title = '查看应用示范系统信息'this.tablabel = '查看应用示范系统信息'this.getInfo()} else if (this.$route.query.type === 'edit') {this.isDisabled = falsethis.$route.meta.title = '编辑应用示范系统信息'this.tablabel = '编辑应用示范系统信息'this.getInfo()} else if (this.$route.query.type === 'add') {this.isDisabled = falsethis.$route.meta.title = '应用示范系统添加'this.tablabel = '应用示范系统添加'}document.title = this.$route.meta.titlethis.setTagsViewTitle()},methods: {changebrowserType() {if (this.form.browserType && this.form.browserType !== '') {this.$refs.form.clearValidate('browserType')}},changepageResolution() {if (this.form.pageResolution && this.form.pageResolution !== '') {this.$refs.form.clearValidate('pageResolution')}},// 修改tagssetTagsViewTitle() {const title = this.$route.meta.titleconst route = Object.assign({}, this.tempRoute, { title: `${title}` })this.$store.dispatch('tagsView/updateVisitedView', route)},// 系统类型切换systemTypeFun() {const str = this.form.systemTypethis.systemTypeFlag = str !== 'Bs'if (str === 'Cs') {this.rules.hardwareEnvironment[0].required = falsethis.rules.browserType[0].required = falsethis.rules.systemUrl[0].required = falsethis.rules.pageResolution0[0].required = falsethis.rules.demoVideo[0].required = true} else {this.rules.hardwareEnvironment[0].required = truethis.rules.browserType[0].required = truethis.rules.systemUrl[0].required = truethis.rules.pageResolution0[0].required = truethis.rules.demoVideo[0].required = false}},// 页面切换是否自适应isAdaptation1Fun() {this.rules.pageResolution0[0].required = falsethis.$refs.form.clearValidate('pageResolution0')const str = this.form.isAdaptation1this.isAdaptation1Flag = str !== '是'if (str === '是') {this.rules.pageResolution[0].required = false} else {this.rules.pageResolution[0].required = true;}},// 获取企业名称下拉框getCompanyNameFun() {const params = {}params.projectId = localStorage.getItem('projectId') === 'null' ? '' : localStorage.getItem('projectId')// params.ExcludeCompanyId = this.ExcludeCompanyId// params.CompanyName = this.ExcludeCompanyName // 模糊搜索getProjectCompanies(params).then((res) => {this.companyList = res.data})},// 平台页面分辨率getResolutionTypesFun() {getResolutionTypes().then((res) => {this.pageResolutionArr = res.data})},// 获取最佳适配浏览器类型getBrowserTypesFun() {getBrowserTypes().then((res) => {this.browserTypesArr = res.data})},// 获取示范地区为省getProvinceFun() {getDemoSystemsProvince().then((res) => {this.provinceArr = res.data})},// 获取示范地区为城市群getCityGroupFun() {getCityGroup().then((res) => {this.cityGroupArr = res.data})},// 获取地区getAreasFun(val, type) {getAreas({ parentId: val }).then((res) => {if (type === 1) {this.provinceArr = [{ areaId: '', areaName: '无' }].concat(res.data)} else if (type === 2) {this.countyArr = [{ areaId: '', areaName: '无' }].concat(res.data)} else if (type === 3) {this.regionArr = [{ areaId: '', areaName: '无' }].concat(res.data)}})},// 选择省/直辖市provincechange(val) {this.form.cityAreaId = ''this.form.areaId = ''this.regionArr = []this.getAreasFun(val, 2)},// 选择citycountychange(val) {this.form.areaId = ''this.getAreasFun(val, 3)},// 回显信息getInfo() {const id = this.$route.query.idconst that = thisgetDemoSystemsDetails(id).then((res) => {const tarobj = res.datathat.form.name = tarobj.namethat.form.systemIntroduction = tarobj.systemIntroductionthat.form.pageResolution = tarobj.pageResolution// 简称that.jianchengArr = tarobj.applicationDemoSystemAliasesthat.form.systemType = tarobj.systemType// 系统类型——平台网址、演示地址if (tarobj.systemType === 'Bs') {that.systemTypeFlag = falsethat.form.systemUrl = tarobj.systemUrl} else {that.systemTypeFlag = truethat.form.demoVideo = tarobj.systemUrl}// 示范城市群tarobj.areaScopes.forEach((item, index) => {const obj = {}obj.areaId = item.provinceAreaIdobj.areaName = item.fullAreaNamethat.selectedCityComplete.push(obj)that.selectedCityGroup.push(item.provinceAreaId)const checkedCount = that.selectedCityGroup.lengththat.isIndeterminate = checkedCount > 0 && checkedCount < this.cityGroupArr.length})// 适配浏览器类型that.form.browserType = tarobj.browserType// 系统开发单位tarobj.companyIds.forEach((item, index) => {that.danweiArr.push(item.companyId)const obj = {}obj.id = item.companyIdobj.name = item.companyNamethat.danweiNameArr.push(obj)})// 运行硬件环境that.form.hardwareEnvironment = tarobj.hardwareEnvironment// 系统联系人及电话that.form.contact = tarobj.contactthat.form.contactCellphone = tarobj.contactCellphone// 是否页面自适应if (tarobj.isAdaptation === true) {that.form.isAdaptation1 = '是'that.isAdaptation1Flag = false} else if (tarobj.isAdaptation === false) {that.form.isAdaptation1 = '否'that.isAdaptation1Flag = true}that.rules.pageResolution0[0].required = false// 平台示范地区const arr = tarobj.demoSystemAreasarr.forEach(function(item, index) {const key = item.areaId ? item.areaId : item.cityAreaId ? item.cityAreaId : item.provinceAreaIditem.key = key})that.areasArr = arr // 应用示范地区// 附件that.form.attachments = tarobj.attachments},err => {if (err.response.status === 403) {this.$message.error(err.response.data.error.message)} else {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)}})},// 添加地区addAreasFun() {if (this.form.provinceid === '') {this.$message({message: '请选择地区',type: 'warning'})} else {const obj = {}obj.provinceAreaId = this.form.provinceid ? this.form.provinceid : nullobj.cityAreaId = this.form.cityAreaId ? this.form.cityAreaId : nullobj.areaId = this.form.areaId ? this.form.areaId : nullobj.key = this.form.areaId ? this.form.areaId : this.form.cityAreaId ? this.form.cityAreaId : this.form.provinceidconst thisLabel1 = this.form.provinceid ? this.provinceArr.find(item => item.areaId === this.form.provinceid).areaName : ''const thisLabel2 = this.form.cityAreaId ? this.countyArr.find(item => item.areaId === this.form.cityAreaId).areaName : ''const thisLabel3 = this.form.areaId ? this.regionArr.find(item => item.areaId === this.form.areaId).areaName : ''obj.fullAreaName = thisLabel1 + '' + thisLabel2 + '' + thisLabel3obj.cityName=thisLabel2 + thisLabel3;if(this.areasArr.find(s=>s.fullAreaName==obj.fullAreaName)!==undefined||this.areasArr.find(s=>s.fullAreaName==obj.cityName)!==undefined){this.$message({message: '请勿重复添加:'+obj.fullAreaName+'',type: 'warning'});}else{this.areasArr.push(obj)if (this.areasArr.length > 0) {this.$refs.form.clearValidate('shifandiqu')}}this.form.provinceid = ''this.form.cityAreaId = ''this.form.areaId = ''this.countyArr = []this.regionArr = []console.log(this.areasArr);}},// 删除地区delAreaFun(val) {const arr = this.areasArrarr.forEach(function(item, index) {if (val === item.key) {arr.splice(index, 1)}})},// 删除城市群delcityGroupFun(val) {const that = thisthis.selectedCityGroup = []const arr = this.selectedCityCompletearr.forEach(function(item, index) {if (val === item.areaId) {arr.splice(index, 1)}})arr.forEach((item, index) => {that.selectedCityGroup.push(item.areaId)})const checkedCount = that.selectedCityGroup.lengththis.isIndeterminate = checkedCount > 0 && checkedCount < this.cityGroupArr.length},// 表单提交checkForm() {// if (this.form.systemUrl === 'Cs') {//   this.rules.systemUrl[0].required = false// } else if (this.form.systemUrl === 'Bs') {//   this.rules.demoVideo[0].required = false// }const proId = localStorage.getItem('projectId')this.$refs['form'].validate((valid) => {if (!valid) returnconst tarObj = { ...this.form }// 项目idtarObj.projectId = proId// 是否页面自适应if (tarObj.isAdaptation1 === '是') {tarObj.isAdaptation = truetarObj.pageResolution="";} else if (tarObj.isAdaptation1 === '否') {tarObj.isAdaptation = false}// 平台示范地区tarObj.demoSystemAreas = this.areasArr// 附件上传tarObj.attachments = this.form.attachments// 简称录入tarObj.applicationDemoSystemAliases = this.jianchengArr// 系统类型if (tarObj.systemType === 'Bs') {tarObj.systemUrl = this.form.systemUrl} else {tarObj.systemUrl = this.form.demoVideo}// 城市群const AreaScopesarr = []this.selectedCityComplete.forEach((item, index) => {const obj = {}obj.provinceAreaId = item.areaIdobj.fullAreaName = item.areaNameAreaScopesarr.push(obj)})tarObj.AreaScopes = AreaScopesarr// 系统开发单位tarObj.companyIds = this.danweiArr// 判断是添加还是修改if (this.$route.query.type === 'add') {createDemoSystems(tarObj).then((res) => {if (res.status === 204) {// this.$router.go(-1)this.$router.push({name: 'resultRegister',query: {tabval: 2}})}},err => {if (err.response.status === 403) {this.$message.error(err.response.data.error.message)} else {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)}})} else if (this.$route.query.type === 'edit') {tarObj.id = this.$route.query.idupdateDemoSystems(tarObj).then((res) => {// this.$router.go(-1)this.$router.push({name: 'resultRegister',query: {tabval: 2}})},err => {if (err.response.status === 403) {this.$message.error(err.response.data.error.message)} else {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)}})}})},// 返回returnFun() {// this.$router.go(-1)this.$router.push({name: 'resultRegister',query: {tabval: 2}})},// 文件上传uploadFile(val) {const FormDatas = new FormData()// console.log('file------', val)// FormDatas.append('fileName', 'ceshi1')FormDatas.append('achievementType', 'DemoSystem')FormDatas.append('file', val.file)uploadFlie(FormDatas).then((res) => {const tarobj = {}const str = val.file.nametarobj.name = str.substring(0, str.length - 4)tarobj.url = res.dataconsole.log('type---', val.file.type)if (val.file.type === 'application/pdf') {tarobj.type = 'Pdf'} else {tarobj.type = 'Video'}const arr = this.form.attachmentsarr.push(tarobj)if (this.form.attachments.length > 0) {this.$refs.form.clearValidate('fujian')}// console.log('this.form.attachments---', this.form.attachments)},err => {if (err.response.status === 403) {this.$message.error(err.response.data.error.message)} else {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)}})},// 视频上传uploadMp4FileFun(val) {const FormDatas = new FormData()FormDatas.append('achievementType', 'Video')FormDatas.append('file', val.file)uploadMp4Flie(FormDatas).then((res) => {this.form.demoVideo = res.data},err => {if (err.response.status === 403) {this.$message.error(err.response.data.error.message)} else {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)}})},// 视频预览viewVedioFun() {const videourl = this.form.demoVideoif (videourl === '') {this.$message({message: '请上传视频',type: 'warning'})} else {window.open(videourl)}},// 修改文件名editName(val) {this.fileUrl = val},// 保存文件名saveName() {this.fileUrl = ''},// 预览pdfpreviewFun(val) {getAttachmentsUrl(val).then((res) => {window.open(res.data)})},// 文件删除handleRemove(val) {deleteUploadFlie(val).then((res) => {if (res.status === 204) {const arr = this.form.attachmentsarr.forEach(function(item, index) {if (val === item.url) {arr.splice(index, 1)}})}},err => {const errmsg = err.response.data.error.validationErrorslet errtext = ''errmsg.forEach((item, index) => {errtext += item.message})this.$message.error(errtext)})},handleSuccess(val) {},// 示范城市群弹窗——全选方法handleCheckAllChange(val) {// val === true/false// this.checkedCities = val ? cityOptions : []// this.selectedCityGroup = val ? this.cityGroupArr : []const newarr = []const newarr2 = []this.cityGroupArr.forEach((item, index) => {// newarr.push(item.areaName)newarr.push(item.areaId)newarr2.push(item)})this.selectedCityGroup = val ? newarr : []this.selectedCityComplete = val ? newarr2 : []this.isIndeterminate = false},// 示范城市群弹窗——单选方法handleCheckedCitiesChange(value) {this.selectedCityComplete = []this.cityGroupArr.forEach((item, index) => {if (value.indexOf(item.areaId) !== -1) {this.selectedCityComplete.push(item)}})const checkedCount = value.lengththis.checkAll = checkedCount === this.cityGroupArr.lengththis.isIndeterminate = checkedCount > 0 && checkedCount < this.cityGroupArr.length},// 城市群弹窗——确定confirmFun() {this.centerDialogVisible = falseif (this.selectedCityComplete.length > 0) {this.$refs.form.clearValidate('shifandiqu')}// console.log('selectedCityGroup===', this.selectedCityGroup)// console.log('cityGroupArr===', this.cityGroupArr)},cityDialogClose() {// this.centerDialogVisible = falsethis.selectedCityGroup = []this.selectedCityComplete = []this.checkAll = falsethis.handleCheckAllChange(false)},// 添加平台简称addKeywordsFun() {if (this.form.jiancheng === '' || this.form.jiancheng === undefined) returnif (this.jianchengArr.indexOf(this.form.jiancheng) !== -1) {this.$message.error('该简称已存在,请勿重复添加!')} else {this.jianchengArr.push(this.form.jiancheng)this.form.jiancheng = ''}},// 删除平台简称delkeywordFun(val) {const arr = this.jianchengArrarr.forEach(function(item, index) {if (val === item) {arr.splice(index, 1)}})},// 添加系统开发单位addKeywordsDanweiFun() {if (this.form.danwei === '' || this.form.danwei === undefined) returnif (this.danweiArr.indexOf(this.form.danwei) !== -1) {this.$message.error('该单位已添加,请勿重复添加!')this.form.danwei = ''return} else {this.danweiArr.push(this.form.danwei)// this.form.danwei = ''}// this.danweiArr.push(this.form.danwei)const obj = {}obj.name = this.companyList.find(item => item.id === this.form.danwei).companyNameobj.id = this.form.danweithis.danweiNameArr.push(obj)if (this.danweiNameArr.length > 0) {this.$refs.form.clearValidate('kaifadanwei')}this.form.danwei = ''},// 删除系统开发单位delDanweikeywordFun(val) {const arr = this.danweiArrarr.forEach(function(item, index) {if (val === item) {arr.splice(index, 1)}})const arr2 = this.danweiNameArrarr2.forEach(function(item, index) {if (val === item.id) {arr2.splice(index, 1)}})}}
}
</script>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com