Praser
Praser

Reputation: 3

how to stop validating numbers stats with zero (0) in php

I am making a php form. I want to validate numerical content in PHP. I am using this PHP code for do it.

if (!preg_match('/^[0-9]*$/',$id)) 
{
    $id_Err = "Only numbers allowed";
}

But this code allows numbers starts with 0.

ex:- 01,02,.....,0100...

I only need to allow nubers like

1,2,....100,...

How can I write this regular expression?

Upvotes: 0

Views: 65

Answers (1)

user764357
user764357

Reputation:

This regex should work.

if (!preg_match('/^[1-9][0-9]*$/',$id)) 
{
    $id_Err = "Only numbers allowed";
}

It forces the regex to match a number from 1-9, and then 0 or more of any digit. This will watch any positive integer greater than zero.

If you want to allow a single zero as well:

if (!preg_match('/^(?:[1-9][0-9]*)$|^0$/',$id)) 
{
    $id_Err = "Only numbers allowed";
}

Upvotes: 1

Related Questions