0
<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

Tushar
  • 85,780
  • 21
  • 159
  • 179
Jack jes
  • 15
  • 2
  • 6

1 Answers1

1

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 ($)

Stefan Dochow
  • 1,454
  • 1
  • 10
  • 11
  • 1
    Better to use `test` instead of `match`, `test` is used to check if string follows some pattern, `match` is used to extract a pattern from string. – Tushar Oct 28 '15 at 04:00
  • I agree. Good point: http://stackoverflow.com/questions/10940137/regex-test-v-s-string-match-to-know-if-a-string-matches-a-regular-expression – Stefan Dochow Oct 28 '15 at 04:02