我写了一些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;
}
}
答案 0 :(得分:11)
只需将它们添加到角色组即可。当然,因为-
和/
在此上下文中都是特殊字符(/
结束了一个RegExp,-
表示一个范围),所以你需要逃脱他们前面有\
:
function validateAddress(){
var TCode = document.getElementById('address').value;
if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
答案 1 :(得分: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
}
}
答案 2 :(得分:0)
function namefun(c)
{
var spch=/[A-z\s]/ig;
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++;
}
}
答案 3 :(得分: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);
}