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

How to start a transaction in MySQL

Preface This article mainly introduces how to sta...

Share 8 very useful CSS development tools

CSS3 Patterns Gallery This CSS3 pattern library s...

Object-Oriented Programming with XHTML and CSS

<br />If only XHTML and CSS were object-orie...

Detailed explanation of Linux text editor Vim

Vim is a powerful full-screen text editor and the...

A link refresh page and js refresh page usage examples

1. How to use the link: Copy code The code is as f...

Docker Swarm from deployment to basic operations

About Docker Swarm Docker Swarm consists of two p...

Pay attention to the use of HTML tags in web page creation

This article introduces some issues about HTML ta...

Teach you how to build the vue3.0 project architecture step by step

Table of contents Preface: 1. Create a project wi...

Detailed explanation of CocosCreator optimization DrawCall

Table of contents Preface What is DrawCall How do...

wget downloads the entire website (whole subdirectory) or a specific directory

Use wget command to download the entire subdirect...

Sample code for changing the color of a png image through a CSS3 filter

This method uses the drop-shadow filter in CSS3 t...

XHTML Getting Started Tutorial: Simple Web Page Creation

Create your first web page in one minute: Let'...

WeChat applet scroll-view realizes left and right linkage

This article shares the specific code for WeChat ...

In-depth understanding of the use of r2dbc in MySQL

Introduction MySQL should be a very common databa...