Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

javascript - Special character validation

I have some javascript written to validate that a string is alphanumeric but i was just wondering how i could add some code to include hyphens(-) and slash's(/) as acceptable inputs. Here is my current code:

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;
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply add them to the character group. Of course, because both - and / are special characters in this context (/ ends a RegExp, - expresses a range), you'll need to escape them with a preceding :

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

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

    return true;     
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...