如何检查字符串是否包含带有react的数字

时间:2019-06-07 08:25:33

标签: reactjs

我正在建立一个用户验证网站,我希望每个输入都可以验证是否输入了字符串:

  1. 首字母大写
  2. 不包含数字
  3. 不包含“ $%^&*()”

我完成了第一个任务,但不能完成最后一个任务。

我已经尝试过!isNaN(firstName) === true,但无法正常工作

import React, { Component } from 'react';

class Profile extends Component {
  state = {
    details: {
      firstName: '',
      lastName: '',
      ID: '',
      Email: ''
    },
    error: false,
    complete: false
  };

  OnSubmit = e => {
    e.preventDefault();
    const { firstName } = this.state.details;
    if (
      firstName.charAt(0) !== firstName.charAt(0).toUpperCase() &&
      !isNaN(firstName) === true
    ) {
      this.setState({ error: true });
    } else {
      this.setState({ complete: true });
    }
  };

  OnChange = e => {
    e.preventDefault();
    this.setState({
      details: { ...this.state.details, [e.target.name]: e.target.value }
    });
  };

  render() {
    return (
      <div>
        <div className="container text-center mt-4" style={{ width: '500px' }}>
          <form className="px-4 py-3" onSubmit={this.OnSubmit}>
            <div className="form-group">
              {this.state.error === true ? (
                <p className="text-danger">
                  Some of the details are wrong check the fields above
                </p>
              ) : null}
              <label>First Name:</label>
              <input
                type="text"
                className="form-control"
                onChange={this.OnChange}
                name="firstName"
              />
            </div>
            <div className="form-group">
              <label>Last Name:</label>
              <input
                type="text"
                className="form-control"
                onChange={this.OnChange}
                name="lastName"
              />
            </div>
            <div className="form-group">
              <label>ID Number:</label>
              <input
                type="text"
                className="form-control"
                onChange={this.OnChange}
                name="ID"
              />
            </div>
            <div className="form-group">
              <label>Email:</label>
              <input
                type="text"
                className="form-control"
                onChange={this.OnChange}
                name="Email"
              />
            </div>
            <button type="submit" className="btn btn-secondary mt-3">
              Check
            </button>
          </form>
        </div>
      </div>
    );
  }
}

export default Profile;

6 个答案:

答案 0 :(得分:4)

function validateName(name) {
  var isValidName = true;
  if(/[!@#$%^&*(),.?":{}|<>]/g.test(name) || !/^[A-Z]/.test(name) || /\d+/g.test(name)) {
    isValidName = false;
  }
  return isValidName;
}

validateName("David")

答案 1 :(得分:3)

您可以使用正则表达式。

!firstName.match(/\d/)

\d检查数字

答案 2 :(得分:0)

首先拆分firstName,然后检查该数组中的数字

OnSubmit = e => {
    e.preventDefault();
    const { firstName } = this.state.details;
    let firstNameArr = firstName.split('');

    for(value of firstName.split('')){
        if (!isNaN(value) {
          this.setState({ error: true });
        } else {
          this.setState({ complete: true });
        }       
    }
  };

答案 3 :(得分:0)

这就是我要做的:

const test1 = "%2mfas1k";
const test2 = '123';
const test3 = 'test';

function test(str) {
  const match = str.match(/\d+/g);
  const isArray = Array.isArray(match);
  if(isArray) return match.map(Number);
  return false
}

// If test return a result not falsy, contains a number
console.log(test(test1)); // [2, 1]
console.log(test(test2)); // [123]
console.log(test(test3)); // false

答案 4 :(得分:0)

这是一个可行的示例,我将每个部分拆分为自己的检查器,以使其更易于理解。

   let string = "Asdfsdf$32";
        let special_characters = ['$','%','^','&','*','(',')'];

        let string_array = string.split('');

        // Upper case check
        if(string[0] === string[0].toUpperCase()) {
            console.log("First letter is uppercase")
        } else {
            console.log("First letter is not uppercase")
        }

        // No numbers check
        if(string.match(/\d/)) {
            console.log("Digit Found")
        } else {
            console.log("No Digit Found")
        }

        // Special Characters
        if(string_array.find(item => special_characters.includes(item))) {
            console.log("Special Character Found")
        } else {
            console.log("No Special Character Found")
        }

答案 5 :(得分:0)

export function checkDigit(username){

    if(username.match(/\d/)) {
        console.log("Digit Found")
        return true;
    }else {
        return false;
    }
}


       let username = this.state.name;

        if(checkDigit(username)){
            showInfoAlert(NAME_VALIDATION_DIGIT)
            return
        }