1

我编写了一些 javascript 来验证字符串是否为字母数字,但我只是想知道如何添加一些代码以包含连字符(-)和斜杠(/)作为可接受的输入。这是我当前的代码:

function validateAddress() {
  var address = document.getElementById('address');

  if (address.value == "") {
    alert("Address must be filled out");
    return false;
  } else if (document.getElementById('address').value.length > 150) {
    alert("Address cannot be more than 150 characters");
    return false;
  } else if (/[^a-zA-Z0-9\-\/]/.test(address)) {
    alert('Address can only contain alphanumeric characters, hyphens(-) and back slashs(\)');
    return false;
  }
}
4

4 回答 4

13

只需将它们添加到字符组中。当然,因为-/在这种情况下都是特殊字符(/结束一个正则表达式,-表示一个范围),你需要用前面的来转义它们\

function validateAddress(){
    var TCode = document.getElementById('address').value;

    if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
        alert('Input is not alphanumeric');
        return false;
    }

    return true;     
}
于 2013-05-21T10:09:59.740 回答
1
function isValidCharacter(txtTitle) {   
     var title = document.getElementById(txtTitle);
     var regExp = /^[a-zA-Z]*$/
     if (!regExp.test(title.value)) {
        title.value = '';
        return false;
        }
      else {      
           return true;
        }
   }


function Validation(){
 var txtTitles = document.getElementById('txtTitle');
  if (isValidCharacter(txtTitles.id) == false) {
   alert("Please enter valid title. No special character allowed.");        
    return false;
  }  
 }



   $("#Btn").unbind("click").click(function () {
        if (Validation() == false) {

        }
        else {
              //success     
        }
   }
于 2014-02-12T12:44:36.100 回答
0

输入:

<input type="text" name="textname" id="tname"  onblur="namefun(this.value)">

Javascript

function namefun(c) {
  var spch = /[A-z\s]/gi;
  var dig = /[0-9]/g;
  var ln = c.length;
  var j = 1;
  for (var i = 0; i < ln; i++) {
    var k = c.slice(i, j);
    if (spch.test(c) == false || dig.test(c) == true) {
      alert("Invalid name");
      document.getElementById("tname").value = "";
      ln = 0;
      setTimeout(function () {
        tname.focus();
      }, 1);
      //return false;
    }
    j++;
  }
}
于 2015-12-01T06:38:10.563 回答
0

简单的 Javascript 版本

isValidCharacter(text) {
  const validCharacterRegex = /^[a-zA-Z]*$/;
  return validCharacterRegex.test(text);
}

打字稿版本

isValidCharacter(text: string): boolean {
  const validCharacterRegex: RegExp = /^[a-zA-Z]*$/;
  return validCharacterRegex.test(text);
}
于 2021-01-12T22:23:36.667 回答