Esha
Esha

Reputation: 63

Validating Zip Code using Regular Expression

I am writing a function in pl/sql to validate zip code. The validation condition is that it should accept only 4 digit number and null as valid code. Below is what i have written:

create or replace function is_valid_zip( p_zip_code in varchar2 )
return boolean
is
begin
           if (length(trim(p_zip_code)))<>4
           then return false;
           elsif (owa_pattern.match(p_zip_code,'\b\d{4}\b'))
           then return true;
           elsif (p_zip_code is null)
           then return true;
           else
           return false;
           end if;
end;

The above code is accepting '!234' as a valid code. I am not sure where i am wrong.Can anybody point out the mistake in the code

Upvotes: 1

Views: 473

Answers (1)

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

Use regex:

^null$|^\d{4}$

You are using \b to mark boundaries. As your input would be only 1234 or null or like that, you can simply use start (^) and end ($) anchors.

Regex Decomposition:

  1. ^null$ - null only.

  2. | - Or.

  3. ^\d{4}$ - Four digit string like 1234.

Regex101

Upvotes: 1

Related Questions