shubham
shubham

Reputation: 21

why it is not working to validate only numbers, not going to true condition

The following function is for validating numbers.

function strictlynumber(obj)
{ 
    var numbers=/^[0-9]+$/;
    if (obj!=numbers)
    {
        alert("please enter numbers only");
        return false;
    }
    return true;
}

Upvotes: 0

Views: 52

Answers (3)

Mamun
Mamun

Reputation: 68933

You have to test the value against the Regex. You can not simply compare the value passed with Regex object in that way. Try the following:

function strictlynumber(obj) { 
  var numbers=/^[0-9]+$/; 
  if (!numbers.test(obj)) { 
    alert("please enter numbers only"); 
    return false; 
  } 
  return true;
}
console.log(strictlynumber(5))

Upvotes: 1

Roshan
Roshan

Reputation: 667

Use regexObject.test(obj) method,

In your code obj!=numbers , is a test of equality , it will always return true.

Modified code :

function strictlynumber(obj)
{ 
    var numbers=/^[0-9]+$/;
    if (!numbers.test(obj))
    {
        alert("please enter numbers only");
        return false;
    }
    return true;
}

Please follow the below link for more info on Regular Expression :

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

Upvotes: 1

Nico
Nico

Reputation: 12683

Your statement obj!=numbers is comparing the regular expression /^[0-9]+$/ to obj

You need to execute the regular expression against the input such as.

function strictlynumber(obj)
{ 
    var numbers=/^[0-9]+$/;
    if (!obj.match(numbers))
    {
        alert("please enter numbers only");
        return false;
    }
    return true;
}

Here we use the match method of a string prototype.

Upvotes: 0

Related Questions