The correct posture of the element UI form validation data

Keywords: Vue

The correct posture of the element UI form validation data

Familiarity needs to be verified. The verification conditions are

  • Must fill in
  • Must be a number
  • Range 0 - 100

Refer to the official documentation of the ElementUI. You can have the following validation rules to verify the first condition:

rules: {
  acquaintance: [{
    required: true,
    message: 'Please enter familiarity',
    trigger: 'blur'
  }]
}

The official document gives an example of such a validation number:

And there is such a paragraph to explain:

Validation of numeric types requires a. Number modifier at the v-model, which is provided by Vue itself to convert the binding value to the number type.

Following the instructions, I added the. number modifier:

<el-form-item label="Familiarity" prop="acquaintance">
  <el-input v-model.number="updatehobby.acquaintance" placeholder="0">
    <template slot="append">%</template>
  </el-input>
</el-form-item>

A second rule was added:

rules: {
  acquaintance: [{
    required: true,
    message: 'Please enter familiarity',
    trigger: 'blur'
  }, {
    type: 'number',
    message: 'Familiarity must be numeric',
    trigger: 'blur'
  }]
}

Finally, I wrote a custom validation to validate the third rule.

My complete verification is as follows:

const validateAcquaintance = (rule, value, callback) => {
  // Input 8 --, value is 8
  // It is estimated that parseInt() / parseFloat() is used internally
  if (value < 0 || value > 100) {
    callback(new Error('Familiarity 0 to 100 %Between'))
  } else {
    callback()
  }
}


rules: {
  acquaintance: [{
    required: true,
    message: 'Please enter familiarity',
    trigger: 'blur'
  }, {
    type: 'number',
    message: 'Familiarity must be numeric',
    trigger: 'blur'
  }, {
    validator: validateAcquaintance, // Custom validation
    trigger: 'blur'
  }]
}

However, the conditions are not met!!! This is an example of official documents!!!

8 -- passed the verification!!!

The problem is that the. Number modifier is automatically converted to a number. In this way, the data can get correct 8, the program has good fault tolerance, but it is not user-friendly, because input 8 - does not prompt the user for input error.

So, my solution here is to give up. Number and use custom validation, manually convert data (string) to number, and then judge. So my custom validation function becomes:

const validateAcquaintance = (rule, value, callback) => {
  if (!value) {
    callback(new Error('Familiarity must be entered'))
  }
  value = Number(value)
  if (typeof value === 'number' && !isNaN(value)) {
    if (value < 0 || value > 100) {
      callback(new Error('Familiarity 0 to 100 %Between'))
    } else {
      callback()
    }
  } else {
    callback(new Error('Familiarity must be numeric'))
  }
}

That's it.

Posted by hawkeyes on Fri, 31 Jan 2020 07:18:55 -0800