Javascript function to check if a field input contains letters and numbers only

Posted: November 17, 2012 in JavaScript Posts
Tags: , , , , , , , , , , , , ,
  1. // Function to check letters and numbers
  2. function alphanumeric(inputtxt)
  3. {
  4.  var letterNumber = /^[0-9a-zA-Z]+$/;
  5.  if((inputtxt.value.match(letterNumber))
  6.   {
  7.    return true;
  8.   }
  9. else
  10.   {
  11.    alert(“message”);
  12.    return false;
  13.   }
  14.   }

To get a string contains only letters and numbers (i.e. a-z, A-Z or 0-9) we use a regular expression /^[0-9a-zA-Z]+$/ which allows only letters and numbers. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

HTML Code

  1. <!–DOCTYPE html>
  2. <html lang=”en”>
  3. <head>
  4. <meta charset=”utf-8″>
  5. form validation – checking all letters and numbers

  6. css’ type=’text/css’ />
  7. </head>
  8. <body onload=’document.form1.text1.focus()’>
  9. <div class=”mail”>
  10. <h2>Enter your Registration Number and Submit</h2>
  11. <form name=”form1″ action=”#”>
  12. <ul>
  13. <input type=’text’ name=’text1’/>
  14. rq”>*Enter numbers and alphabets only.
  15. &nbsp;
  16. <input type=”submit” name=”submit” value=”Submit” onclick=”alphanumeric(document.form1.text1)” />
  17. &nbsp;
  18. </ul>
  19. </form>
  20. </div>
  21. <script src=”check-letters-numbers.js”></script>
  22. </body>
  23. </html>

Javascript code

  1. function alphanumeric(inputtxt)
  2. {
  3. var letters = /^[0-9a-zA-Z]+$/;
  4. if(inputtxt.value.match(letters))
  5. {
  6. alert(‘Your registration number have accepted : you can try another’);
  7. document.form1.text1.focus();
  8. return true;
  9. }
  10. else
  11. {
  12. alert(‘Please input alphanumeric characters only’);
  13. return false;
  14. }
  15. }

CSS Code

  1. li {list-style-type: none;
  2. font-size: 16pt;
  3. }
  4. .mail {
  5. margin: auto;
  6. padding-top: 10px;
  7. padding-bottom: 10px;
  8. width: 400px;
  9. background : #D8F1F8;
  10. border: 1px soild silver;
  11. }
  12. .mail h2 {
  13. margin-left: 38px;
  14. }
  15. input {
  16. font-size: 20pt;
  17. }
  18. input:focus, textarea:focus{
  19. background-color: lightyellow;
  20. }
  21. input submit {
  22. font-size: 12pt;
  23. }
  24. .rq {
  25. color: #FF0000;
  26. font-size: 10pt;
  27. }

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s