user7850002
user7850002

Reputation:

Regular expression to check only alphabets

I am trying to achieve form validation of only alphabets but this regular expression doesnt seem to work

 function check() {
      var reg="/^[a-zA-Z]*$/";
    var x = document.forms['frm'].name.value;
    var y=  document.forms['frm'].email.value;

    if( x === ""){
     alert('Name field cant be empty');
     $("#nameone").focus();
      return false;
    }
    else if (!reg.match(x)){
      alert('NAME must contain alphabets only');
      return false;
    }

    else if( y === ""){
     alert('Email  field cant be empty');
     $("#emailone").focus();
      return false;
    }



    else {
      return true;
    }
    }

this is my form ,i have added the details ,the input fields

 <form class="reg_form" name='frm' method="post" onsubmit='return check();' >
     <div class="input-field col-md-4">
      <input type="text" placeholder="1. Name" name="name" id='nameone'/>
    </div>
    <div class="input-field col-md-4">
      <input type="text" placeholder="2. Email" name="email" id='emailone'  />
    </div>
    <div class="input-field col-md-4 ">
     <input type="text" placeholder="3. phone" name="phone" />
     </div>

</form>

Upvotes: 1

Views: 1914

Answers (3)

Diego Cesar
Diego Cesar

Reputation: 31

In this case, your code isn't working 'cause your regex was set as a string in the line:

 var reg="/^[a-zA-Z]*$/";

The regex was suposed to be set without quotes:

 var reg=/^[a-zA-Z]*$/;

I suggest that instead of the method 'match', you use:

else if (!reg.test(x)){

This is more performatic and return a boolean value.

Upvotes: 2

Peter B
Peter B

Reputation: 24147

Instead of...

var reg = "/^[a-zA-Z]*$/"; // produces a **string**

You should omit the surrounding quotes:

var reg = /^[a-zA-Z]*$/;  // produces a **Regex object**

The second uses javascript inline Regex syntax, with the slashes functioning as delimiters.

Furthermore you can use the simple .test() function to check if a string conforms to a Regex or not.

Demo:

var reg = /^[a-zA-Z]*$/;
console.log(reg.test("ABcd"));
console.log(reg.test("123"));

Upvotes: 1

ahmad abdalla
ahmad abdalla

Reputation: 1

you can use

string.match("^[a-zA-Z]+$$");

you will get true if the string contains only letters and false otherwise

Upvotes: 0

Related Questions