Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  164] [ 1]  / answers: 1 / hits: 91838  / 11 Years ago, tue, may 21, 2013, 12:00:00

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;
}
}

More From » function

 Answers
2

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;
}

[#78111] Sunday, May 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;