iview implements dynamic form and custom verification time period overlap

iview implements dynamic form and custom verification time period overlap

Dynamically adding form items

iview's dynamic form addition is very simple. You just need to set the form items to an array, and push a default value when adding a new item. iview will do the rest for you.

<template lang="html">
 <div class="">

    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="rulesValidate"
      :label-width="100"
      :label-colon="true"
    >
   <FormItem
    v-for="(item, index) in formValidate.showTimeDurations"
    :key="index"
    :prop="'showTimeDurations[' + index + '].value'"
    :label="'Show time period' + (index + 1)"
   >
    <Row>
     <TimePicker
      type="timerange"
      v-model="item.value"
      placement="bottom-end"
      placeholder="Select a time period"
      style="width: 400px;"
      :disabled="isDisEdit"
      ></TimePicker>
     <Button shape="circle" icon="md-close" @click="handleRemove(index)" style="margin-left: 10px;"></Button>
    </Row>
   </FormItem>
   <FormItem style="width: 500px;" v-if="formValidate.showTimeDurations.length < 3">
    <Button type="dashed" long @click="handleAddDuration" icon="md-add">Add display period</Button>
   </FormItem>
   </Form>
 </div>
</template>

<script>
export default {
 name: 'banner_new',
 data() {
  return {
   formValidate: {
    showTimeDurations: [{value: ['','']}]
   }
  }
 },
 methods: {
  handleAddDuration() {
   this.formValidate.showTimeDurations.push({value: ['','']})
  },
  handleRemove(index) {
   this.formValidate.showTimeDurations.splice(index, 1)
  }
 }
}
</script>

<style lang="css" scoped>
</style> 

Form Validation

iview's form validation is done by adding the attribute :rules="rulesValidate" RulesValidate is the method set in methods.

Add a title form item and submit button

 <FormItem label="Name" prop="title" style="width: 500px;">
    <Input v-model="formValidate.title" :disabled="isDisEdit" :placeholder="'Please enter the name of the slideshow (up to 50 characters)'" maxlength="50" show-word-limit></Input>
  </FormItem>
  ...
  <Row type="flex" justify="start" style="margin-top: 20px;">
    <Button type="primary" style="width: 100px; margin-left: 20px;" v-if="isCanSave" @click="handleSubmit('formValidate')">Save</Button>
  </Row>
  methods: {
    handleSubmit(form) {
      // Calling the validate method will perform validation this.$refs[form].validate(validate => {
        // validate=true/false, whether the verification is successful or not})
    },
  }

Form Validation:

rulesValidate: {
  title:
    {
      required: true,
      message: 'Please fill in the name of the slideshow',
      trigger: 'blur'
    },
    {
      type: 'string',
      max: 50,
      message: 'Within 50 characters, Chinese/letters/numbers/common characters',
      trigger: 'change'
    }
  ],

It can also be written as

title: [{{ required: true, message: 'Please fill in the image name', trigger: 'blur'}}]

The verification condition is an array and multiple conditions can be written. If you need custom validation, you can define a validator in data

data() {
  const durationValitator = (rule, value, callback) => {
    if(this.isShowTimePicker && value.toString() === ',') {
      callback(new Error('Please select the display time period'));
    }else if(value[0] === value[1]) {
      callback(new Error('Please select the correct time period'))
    }else if(!showTimeDurationsJudge(this.formValidate.showTimeVOS)){
      callback(new Error('Time period cannot be repeated'))
    }else {
      callback()
    }
  };
  const durationValidate = [{ validator: durationValitator, trigger: 'blur' }];
  return {
    rulesValidate: {
      'showTimeDurations[0].value': durationValidate,
      'showTimeDurations[1].value': durationValidate,
      'showTimeDurations[2].value': durationValidate,
    }
  }
}

'showTimeDurations[0].value': durationValidate, this way of writing means validating the value of the first sub-item in the dynamic item of the form. If there are 3 sub-items, it needs to be repeated 3 times. I wonder if there is a better way of writing it? That’s it for now.

showTimeDurationsJudge is a method that verifies that time periods are repeated.

Verify that time periods overlap

First consider how to verify if there are 2 periods of time? The situation of crossing days is not considered.

The result of thinking is that the necessary and sufficient condition for two time periods not to overlap is

  • The start time (start1) and end time (end1) of the previous period (a1) must be before the start time (start2) of the next period (a2)
  • The start time (start2) and end time (end2) of the next period (a2) must be after the end time (end1) of the previous period (a1)

Meeting the above conditions can ensure that the two time periods are completely staggered.

Because the time given by the control is a string in the format of "00:00:00", I introduced the moment library to convert the string into a timestamp, which can be compared in size.

const judge = (a1,a2) => {
 let result = false
  const start1 = moment(a1[0],"HH:mm:ss").valueOf()
  const end1 = moment(a1[1],"HH:mm:ss").valueOf()
  const start2 = moment(a2[0],"HH:mm:ss").valueOf()
  const end2 = moment(a2[1],"HH:mm:ss").valueOf()

  if(start1 == start2) {
    return false
  }else if(start1 > start2) {
    result = start1 > end2
  }else {
    result = end1 < start2
  }
  return result
}

If there is overlap, it returns false; if there is no overlap, it returns true. After being able to compare two time periods, if there are more time periods, you can use a loop to compare them. The complete code is:

import moment from 'moment'

export const showTimeDurationsJudge = (durations) => {
 let judgeResult = true
 if (durations && durations.length > 1) {
  for(let i=0;i<durations.length-1;i++){
   for(let j=i+1;j < durations.length; j++) {
       judgeResult = judgeResult && judge(durations[i].value,durations[j].value)
     }
  }
 }
 return judgeResult
}

const judge = (a1,a2) => {
 let result = false
  const start1 = moment(a1[0],"HH:mm:ss").valueOf()
  const end1 = moment(a1[1],"HH:mm:ss").valueOf()
  const start2 = moment(a2[0],"HH:mm:ss").valueOf()
  const end2 = moment(a2[1],"HH:mm:ss").valueOf()

  if(start1 == start2) {
    return false
  }else if(start1 > start2) {
    result = start1 > end2
  }else {
    result = end1 < start2
  }
  return result
}

This concludes this article about how iview implements dynamic forms and custom verification time period overlap. For more relevant iview form verification content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on iview form validation
  • Summary of iview's simultaneous verification of multiple forms

<<:  JavaScript canvas text clock

>>:  jQuery implements accordion effects

Recommend

Implementing parameter jump function in Vue project

Page Description:​ Main page: name —> shisheng...

Linux kernel device driver virtual file system notes

/******************** * Virtual File System VFS *...

Bootstrap 3.0 study notes grid system case

Preface In the previous article, we mainly learne...

How to support Webdings fonts in Firefox

Firefox, Opera and other browsers do not support W...

About input file control and beautification

When uploading on some websites, after clicking t...

The difference between html empty link href="#" and href="javascript:void(0)"

# contains a location information. The default anc...

Deeply understand how nginx achieves high performance and scalability

The overall architecture of NGINX is characterize...

The difference between animation and transition

The difference between CSS3 animation and JS anim...

Vue batch update dom implementation steps

Table of contents Scene Introduction Deep respons...

Pure CSS header fixed implementation code

There are two main reasons why it is difficult to...

View the command to modify the MySQL table structure

Brief description The editor often encounters som...