You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Semantic-UI-React实现仅允许小数输入的表单验证?

Hey there! Let's tackle this validation issue for your Semantic UI React form—no need for complex libraries like redux-form if you don't want it. Here's a straightforward, component-level approach that works perfectly for validating decimal distance values:

1. Controlled Component + Local State Management

First, turn your input into a controlled component using React's useState to manage the input value and error state. This lets you control the input content in real time and give immediate feedback to users.

Example Code

import { useState } from 'react';
import { Form, Button } from 'semantic-ui-react';

const SearchForm = () => {
  const [distance, setDistance] = useState('');
  const [error, setError] = useState('');

  // Validation function: check for valid positive decimal values
  const validateDistance = (value) => {
    // Regex matches positive integers or decimals (e.g., 5, 5.0, 0.5, 123.456)
    const decimalRegex = /^[0-9]+(\.[0-9]+)?$/;
    
    if (!value.trim()) {
      return 'Distance is required';
    }
    if (!decimalRegex.test(value)) {
      return 'Please enter a valid positive decimal number';
    }
    // Optional: add range validation (e.g., distance can't be 0 or exceed 1000)
    const numValue = parseFloat(value);
    if (numValue <= 0) {
      return 'Distance must be greater than 0';
    }
    return '';
  };

  const handleChange = (e) => {
    const inputValue = e.target.value;
    setDistance(inputValue);
    // Real-time validation (remove this if you only want validation on submit)
    const validationError = validateDistance(inputValue);
    setError(validationError);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const validationError = validateDistance(distance);
    
    if (validationError) {
      setError(validationError);
      return;
    }
    // Validation passed: execute your submit logic here
    console.log('Valid distance submitted:', distance);
    // Call your API or handle search functionality
  };

  return (
    <Form onSubmit={handleSubmit} error={!!error}>
      <Form.Field>
        <label>Distance</label>
        <input
          type="text"
          value={distance}
          onChange={handleChange}
          placeholder="Enter distance (e.g., 5.5)"
        />
      </Form.Field>
      {error && <Form.Error content={error} />}
      <Button type="submit" disabled={!!error}>Search</Button>
    </Form>
  );
};

export default SearchForm;
2. Key Details
  • Controlled Component: Binding the input value to useState ensures you have full control over the input content and validation state.
  • Regex Validation: The regex /^[0-9]+(\.[0-9]+)?$/ matches valid positive decimals—adjust it if you need to support negative values (though distance should probably stay positive).
  • Real-Time vs. Submit-Time Validation: The example uses real-time validation, but you can remove the validation call in handleChange if you prefer to only check for errors when the user clicks submit.
  • SUIR Error Integration: Using <Form.Error> with the Form component's error property automatically applies Semantic UI's error styling, keeping your UI consistent.
3. Bonus: Restrict Invalid Input (Optional)

If you want to prevent users from typing invalid characters (like letters or multiple decimals) entirely, add a filter in the handleChange function:

const handleChange = (e) => {
  // Allow only numbers and a single decimal point
  const filteredValue = e.target.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
  setDistance(filteredValue);
  const validationError = validateDistance(filteredValue);
  setError(validationError);
};

This filters out unwanted characters as the user types, making the validation process smoother.

This solution relies solely on React's native state and Semantic UI React components—no extra dependencies required, and it's easy to maintain and adjust to your specific needs.

内容的提问来源于stack exchange,提问作者Anouar Bellakha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:23:18