user3298056
user3298056

Reputation: 7

Validate username in html

I want that the textbox followed by username should accept only alphabets or digits or their combination.If user enters anything except alphabets or digits then alert dialog box should appear when button is clicked.My code is:

 <html>
 <body>

 <form name="f1">
 username <input type="text" name="tb1"><br>
 <input type="button" value="validate" onclick="val()">
 </form>

 <script>
 function val()
 {
if(document.f1.tb1.value=="")
    alert('Enter username!');
 }
 </script>

 </body></html>

Can anyone tell me the solution?

Upvotes: 1

Views: 277

Answers (2)

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

how about this ?:

EDITED:

function val()
{
    if(document.f1.tb1.value == null || 
       document.f1.tb1.value == undefined ||
       /[^a-zA-Z0-9]+/.test(document.f1.tb1.value))

      alert('invalid username!');
 }

Upvotes: 0

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

Use a regex in your val function:

function val()
{
    if(document.f1.tb1.value=="")
        alert('Enter username!');
    if(/[^a-zA-Z0-9]/.test(document.f1.tb1.value))
        alert('Username must only consist of letters and numbers')
}

What this line does is look to see if the string you pass to test has anything other than a-z, A-Z, and 0-9. If it does, then it gives the alert. If you're willing to accept an underscore as a valid character, then the if becomes much simpler:

if(/[\W]/.test(document.f1.tb1.value))

\w is a shortcut that represents all numbers, characters, and the underscore. The [^...] syntax means "any character that doesn't match this list. \W actually is a shortcut for [^\w], and looks for anything that isn't A-Z, a-z, 0-9 and _.

Edit, per your comment

If you only want to accept alphabetic characters, you just test for the a-z instead of adding the 0-9 in your expression:

if(/[^a-zA-Z]/.test(document.f1.tb1.value))

This checks the value of document.f1.tb1.value to see if it has anything that's not a letter, i.e. anything outside of a-z and A-Z.

There is lots of documentation out there regarding regular expressions. Once you understand the concept, I use MDN as a reference.

Upvotes: 2

Related Questions