Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code does not pass first validation

I have a function in which I am first checking that a string passed as argument has letters only or not. But it always return as false. Below is my jsfiddle

function takeString (str) {
    var regex = "/^[A-Za-z]+$/";

    if (str.match(regex)) {
        if (str.charCodeAt(0) === str.toUpperCase().charCodeAt(0)) {
            alert('true');
            return true;
        } 
        else {
            alert('false');
            return false;
        }
    } 
    else {
        alert('Only letters please.');
    }
}

takeString('string');

​ The above code always alerts Only letters please.

like image 218
Om3ga Avatar asked Dec 06 '12 13:12

Om3ga


People also ask

What happens when a validator fails?

If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.

What is a code validation?

What Is a Validation Code? A validation code—also known as a CVV, CV2, or CVV2 code—is a series of three or four numbers located on the front or back of a credit card. It is intended to provide an additional layer of security for credit card transactions that take place online or over the phone.

What does validation error mean?

Validations errors are errors when users do not respond to mandatory questions. A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).


1 Answers

You need to get rid of the quotes to make regex a regular expression literal:

var regex = /^[A-Za-z]+$/;

Here's an updated fiddle.

Currently, regex refers to a string literal. When you pass something that's not a regular expression object or literal to String#match, it implicitly converts that argument to a regular expression object (see ES5 15.5.4.10):

  • If Type(regexp) is Object and the value of the [[Class]] internal property of regexp is "RegExp", then let rx be regexp;
  • Else, let rx be a new RegExp object created as if by the expression new RegExp( regexp) where RegExp is the standard built-in constructor with that name.

Your regular expression is therefore interpreted like this (since the string contains the forward slash characters you were expecting to delimit a regular expression literal):

var regex = /\/^[A-Za-z]+$\//;

That can't match anything, since it's looking for a forward slash, followed by the start of the string.

like image 97
James Allardice Avatar answered Sep 19 '22 20:09

James Allardice