Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  161] [ 7]  / answers: 1 / hits: 15654  / 11 Years ago, mon, january 13, 2014, 12:00:00

To restrict an input field to alphanumeric only, I use the following on my site:



  <input 
type=text
name=url_code
pattern=[a-zA-Z0-9_-]{4,10}
class=widefat-main
title=4 to 10 alphanumerical characters only
/>


However for browsers that don't support HTML5, what is the best way to get the same restrictions?


More From » html

 Answers
13

You will need to use JavaScript to check the input then. In your <form> tag, the onsubmit attribute needs to call a function that will return a boolean value. True means that the form will go through, false, means that it won't.



Use a document selector to get the input element and then check its value attribute. Make sure it is the right length. Then match it against a regular expression. (Learn about them here: Regular Expressions) If everything thing is fine, return true. Otherwise return false and either print in the console what was wrong or write it to a <div>. If you want a pop-up like you get with the HTML5 way, you'll have to do some other magic.



Note the return validate(); If you don't include that in your onsubmit= then it won't work, you must have the return.



<!DOCTYPE html>
<html>
<head>
<title>Validate</title>
<meta charset=UTF-8>
<meta name=viewport content=width=device-width>
<style>
.widefat-main{
}
</style>
<script>
function validate() {
var errorDiv = document.getElementById(errorDiv),
regex = /^[a-z0-9]+$/,
str = document.getElementById(inputString).value;

if ((str.length > 4) && (str.length < 10) && regex.test(str)) {
errorDiv.innerHTML = Fine string;
return true;
}
else {
errorDiv.innerHTML = 4 to 10 alphanumerical characters only;
return false;
}
}
</script>
</head>
<body>
<form action= onsubmit=return validate();>
<input
id=inputString
type=text
name=url_code
class=widefat-main
title=4 to 10 alphanumerical characters only
/>
<input type=submit value=Submit/>
</form>
<div id=errorDiv></div>
</body>
</html>

[#73195] Sunday, January 12, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;