我如何编写正则表达式以仅接受antd输入的数字

时间:2019-03-15 12:16:32

标签: regex reactjs antd

我必须在我的antd输入字段中输入数字。但是它接受数字和字母。对于我的需求,逻辑工作正常,但字母除外。那么,我该怎么假设写一个只接受数字的正则表达式呢?

import React from 'react'
import * as AntD from "antd";
import { Input, Tooltip } from 'antd';
const { Row, Col } = AntD;

function creditCardFormatter(value) {
  var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
  var matches = v.match(/\d{4,16}/g);
  var match = matches && matches[0] || '';
  var parts = [];
  for (let i = 0, len = match.length; i < len; i += 4) {
    parts.push(match.substring(i, i + 4));
    console.log(parts)
    console.log(match)}
  if (parts.length){
    console.log(parts.length)
    return parts.join(' ');
  } else {
    return value;
  }
}
//     value += '';
//     const list = value.split('.');
//     const prefix = list[0].charAt(0) === '-' ? '-' : '';
//     let num = prefix ? list[0].slice(2) : list[0];
//     let result = '';
//     while (num.length > 4) {
//       result = ` ${num.slice(-4)}${result}`;
//       num = num.slice(0, num.length - 4);
//     }
//     if (num) {
//       result = num + result;
//     }  
//     return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
// }
class NumericInput extends React.Component {


  onChange = (e) => {
    const { value } = e.target;
    this.props.onChange(creditCardFormatter(value));
  }

  render() {
    const { value } = this.props;

    return (

      <div align="center">
        <Col push={5}>
          <label>Enter Number Here :</label>
          <br />
          <Input
            {...this.props}
            onChange={this.onChange}
            placeholder="Input a number"
          />
        </Col>
      </div>
    );
  }
}

class InputElement extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }
  onChange = (value) => {
    this.setState({ value });
  }
  render() {
    return <NumericInput style={{ width: 120 }} value={this.state.value} onChange={this.onChange} />;
  }
}    

export default InputElement

3 个答案:

答案 0 :(得分:3)

对于数字,您只能在antd中始终使用InputNumber

如果您不想使用它,那么您仍然不必编写onchange函数,antd允许您在字段上添加validation rules。 例如:

def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
             labels, num_labels, use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
    config=bert_config,
    is_training=is_training,
    input_ids=input_ids,
    input_mask=input_mask,
    token_type_ids=segment_ids,
    use_one_hot_embeddings=use_one_hot_embeddings)

# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use model.get_sequence_output()
# instead.
output_layer = model.get_pooled_output()

hidden_size = output_layer.shape[-1].value

with tf.variable_scope("cls/seq_relationship"):
    output_weights = tf.get_variable(
        "output_weights", [num_labels, hidden_size])

    output_bias = tf.get_variable(
        "output_bias", [num_labels])

with tf.variable_scope("loss"):
    if is_training:
        # I.e., 0.1 dropout
        output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)

    logits = tf.matmul(output_layer, output_weights, transpose_b=True)
    logits = tf.nn.bias_add(logits, output_bias)
    probabilities = tf.nn.softmax(logits, axis=-1)
    log_probs = tf.nn.log_softmax(logits, axis=-1)

    one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)

    per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
    loss = tf.reduce_mean(per_example_loss)

    return (loss, per_example_loss, logits, probabilities)

现在仅数字正则表达式使用此

{getFieldDecorator("testNumber", {
        rules: [
          {
            required: true,
            type: "regexp",
            pattern: new RegExp(/\d+/g),
            message: "Wrong format!"
          }
        ]
      })(<Input />)}

答案 1 :(得分:1)

对于仅数字,您可以将类型设置为“数字”:https://github.com/yiminghe/async-validator#type

对于您的用例,我认为regexp更复杂。

答案 2 :(得分:0)

尝试使用onChange函数:

onChange = (e) => {
 const { value } = e.target;
 const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
 if ((!Number.isNaN(value) && reg.test(value)) || value === '' || value === '-') {
  this.props.onChange(value);
 }
}