Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Non-Negative Numeric Input Validation with Range Constraints

Tech 2

This article demonstrates how to implement a numeric input component with specific validation requirements: non-negative values, maximum value of 9999, support for up to three decimal places, and ensuring the maximum value is greater than or equal to the minimum value.

Component Structure

<template>
  <div class="range-input-container">
    <el-input 
      v-model="rangeValues.minValue" 
      placeholder="Minimum value" 
      @blur="handleBlur('minValue', rangeValues.minValue)" 
      @input="handleInput('minValue', rangeValues.minValue)">
    </el-input>
    ~
    <el-input 
      v-model="rangeValues.maxValue" 
      placeholder="Maximum value" 
      @blur="handleBlur('maxValue', rangeValues.maxValue)" 
      @input="handleInput('maxValue', rangeValues.maxValue)">
    </el-input>
  </div>
</template>

Data Strucutre

data() {
  return {
    rangeValues: {
      minValue: "",
      maxValue: "",
    },
  };
},

Input Validation Logic

methods: {
  handleInput(fieldName, inputValue) {
    const numericValue = Number(inputValue);
    const hasDecimalPoint = this.containsDecimalPoint(this.rangeValues[fieldName]);
    
    // Validate numeric input
    if (isNaN(numericValue)) {
      this.showWarningMessage("Only numeric values are allowed");
      this.rangeValues[fieldName] = "";
      return;
    }
    
    // Validate maximum value constraint
    if (numericValue > 9999) {
      this.showWarningMessage("Maximum allowed value is 9999");
      this.rangeValues[fieldName] = inputValue.slice(0, 4);
      return;
    }
    
    // Validate decimal precision
    if (hasDecimalPoint) {
      const decimalCount = this.getDecimalPlaces(inputValue);
      if (decimalCount > 3) {
        this.showWarningMessage("Maximum of 3 decimal places allowed");
        this.rangeValues[fieldName] = inputValue.slice(0, -1);
      }
    }
  },
  
  handleBlur(fieldName, currentValue) {
    // Remove trailing decimal point
    if (this.containsDecimalPoint(currentValue)) {
      const decimalCount = this.getDecimalPlaces(currentValue);
      if (decimalCount === 0) {
        this.rangeValues[fieldName] = currentValue.slice(0, -1);
      }
    }
    
    // Validate range consistency
    this.validateRange(this.rangeValues.minValue, this.rangeValues.maxValue);
  },
  
  validateRange(minValue, maxValue) {
    if (minValue && maxValue && Number(maxValue) < Number(minValue)) {
      this.showWarningMessage("Maximum value must be greater than or equal to minimum value");
    }
  },
  
  showWarningMessage(message) {
    this.$message({
      showClose: true,
      message: message,
      iconClass: "warning-icon-class",
      customClass: "el-message--warning",
    });
  },
  
  containsDecimalPoint(value) {
    return value && value.includes('.');
  },
  
  getDecimalPlaces(value) {
    if (!value || !value.includes('.')) return 0;
    return value.split('.')[1].length;
  },
},

Styling

::v-deep .range-input-container {
  width: 220px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid #e1e6f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-input {
    width: 100px;
    height: 30px !important;
    display: flex;
    align-items: center;

    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }

    input[type="number"] {
      -moz-appearance: textfield;
      line-height: 1;
    }

    input {
      border: none;
    }

    .el-input__inner {
      width: 100px;
      height: 30px !important;
      line-height: 30px;
      text-align: center;
      border: none;
    }
  }
}

.range-input-container:hover {
  border: 1px solid #3886ff;
}

Key Features

  1. Non-negative validation: The component only accepts numeric values, rejecting any non-numeric input including negative signs.
  2. Maximum value limit: Values cannot exceed 9999.
  3. Decimal precision: Supports up to three decimal places.
  4. Range validation: Ensures the maximum value is always greater than or equal to the minimum value.
  5. User feedback: Provides clear warning messages for invalid inputs.
  6. Clean input handling: Removes trailing decimal points when the input field loses focus.

Usage Notes

  • The component uses Vue.js with Element UI for the input elements
  • All validation occurs in real-time during user input
  • The styling creates a cohesive range input component with proper hover effects
  • The implementation prevents negative values by rejecting any non-numeric input

Range Input Component

This implementation provides a robust solution for numeric range inputs with specific validation requirements, suitable for applicaitons requiring precise numeric input controls.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.