Jack jes
Jack jes

Reputation: 15

username validation using javascript by document.getElementbyid()

<form method="POST" name="myform" action="<?php $_SERVER['PHP_SELF']; ?>" onsubmit="return validate();">Firstname
    <input type="text" name="firstname" id="firstname">
    <br/>
    <br/>
</form>

My JavaScript validation is

function validate() {

    var A = document.getElementById("firstname").value;
    if (A !== /^[a-zA-Z]/) {
        alert("enter letters only");
        return false;
    }

I want only alphabet letters to enter and if numbers entered means the alert will be displayed.Can any one help me

Upvotes: 0

Views: 2942

Answers (1)

Stefan Dochow
Stefan Dochow

Reputation: 1454

you have to properly check, if the Regex matches the string:

function validate () {

   var A = document.getElementById("firstname").value;
   if(!(/^[a-z]+$/i.test(A)))
   {
      alert ("enter letters only");
      return false;
   }
}

Additionally the regexp neded to make sure that there is at least one character entered (that is done by the + modificator) and that the a-zA-Z rule applies from start (^) to end ($)

Upvotes: 1

Related Questions