需求:一个页面多个经纬度需要经验,然后采用此方法就可以一步到位啦
1.在util.js全局写经纬度的范围校验
代码如下:
const formValidation = {
//经度
validatorLongitude: (rule, value, callback) => {
const reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,15})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,15}|180)$/
if(value === ""){
callback(new Error('请输入经度'));
}else{
if(!reg.test(value)){
callback(new Error('经度范围:-180~180(保留小数点后十五位)'));
}
callback();
}
},
//纬度
validatorLatitude: (rule, value, callback) => {
const reg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,15}|90\.0{0,15}|[0-8]?\d{1}|90)$/
if(value === ""){
callback(new Error('请输入纬度'));
}else{
if(!reg.test(value)){
callback(new Error('纬度范围:-90~90(保留小数点后十五位)'));
}
callback();
}
},
}
export default formValidation
然后在main.js引入
代码如下:
// 经纬度验证
import formValidation from "../src/util/formValidation"
Vue.prototype.formValidation = formValidation;
最后在你需要的页面上这样写:
代码如下:
<el-form :model="machineAdd" :rules="rules" ref="machineAdd" label-width="100px">
<el-row :gutter="20">
<el-col :span="10">
<div class="grid-content bg-purple">
<el-form-item label="设备名称">
<el-input v-model="machineAdd.machineName" placeholder="请输入设备名称"></el-input>
</el-form-item>
</div>
</el-col>
<el-col :span="10">
<div class="grid-content bg-purple">
<el-form-item label="经度" prop="longitude">
<el-input v-model="machineAdd.longitude" placeholder="请输入经度"></el-input>
</el-form-item>
</div>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="10">
<div class="grid-content bg-purple">
<el-form-item label="机巢序列号" prop="serialNumber">
<el-input v-model="machineAdd.serialNumber" maxlength="24" placeholder="请输入机巢序列号"></el-input>
</el-form-item>
</div>
</el-col>
<el-col :span="10">
<div class="grid-content bg-purple">
<el-form-item label="纬度" prop="latitude">
<el-input v-model="machineAdd.latitude" placeholder="请输入纬度"></el-input>
</el-form-item>
</div>
</el-col>
</el-row>
</el-form>
rules这个表单验证统一写一个就好啦~
longitude: [
{
required: true,
//此处的'formValidation'不可随着:model改变而改变,因为formValidations.js已经定义好的,全局使用
validator: this.formValidation.validatorLongitude,
message: "经度范围:-180~180(保留小数点后十五位)",
trigger: "blur"
}
],
latitude: [
{
required: true,
validator: this.formValidation.validatorLatitude,
message: "纬度范围:-90~90(保留小数点后十五位)",
trigger: "blur"
}
],
这样不管你一个页面多个经纬度需要校验,都可以一步到位啦,这样就不需要写很多相同的代码了
标签:经纬度,formValidation,180,value,JS,callback,正则,90 From: https://blog.51cto.com/u_15335909/7492893