0

I have two ways to check a string for a special characters in 11g

1 ) Using SELECT

V_CNT_QRY := ' SELECT LENGTH(TRIM(TRANSLATE(:1,
                                             ''
                                             abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '',
                                             '' '')))
                  from dual ';
EXECUTE IMMEDIATE  V_CNT_QRY INTO V_CNT USING V_COLUMN_DATA;

2) Using a procedure

CREATE OR REPLACE PROCEDURE Validate_Inputstring(input_String IN VARCHAR2) AS
BEGIN
  IF REGEXP_LIKE(input_String, '^[A-Z0-9a-z]*$') THEN
    DBMS_OUTPUT.PUT_LINE('U have entered alphanumeric chars--->' ||
                         input_String);
  ELSE
    DBMS_OUTPUT.PUT_LINE('U NOT have entered alphanumeric chars---->' ||
                         input_String);
  END IF;
END;

Please suggest a better way

2
  • Why not put the expression from the former in a function? Commented Mar 25, 2011 at 11:20
  • What I mean is: there's no need to type in the translate call every time you need it. You can just create a function for it and hide all the ugly details. Commented Mar 25, 2011 at 23:05

3 Answers 3

2

Supposing you want to check if the string contains only ASCII characters, you can use this:

Select 'No'
  From dual
 Where LENGTH(ASCIISTR(:input_String)) != LENGTH(:input_String)
 Union
Select 'Yes'
  From dual
 Where LENGTH(ASCIISTR(:input_String)) = LENGTH(:input_String)

HTH

Sign up to request clarification or add additional context in comments.

Comments

2

I would use the regexp_replace function in the following way:

select 'You have'|| decode(regexp_replace (:txt,'^[A-Z0-9a-z]*$', '1'), '1', ' ', ' not ')  || 'entered a string composed only by alphanum characters' from dual;

The bind variable txt contains the string to validate.

Comments

1
create table testx
( val1 varchar2(50));

insert into testx (val1) values ('Some ' || chr(9) || 'bad string');
insert into testx (val1) values ('Some nice string with 123 numbers');
commit;

select val1, regexp_instr(val1, '[^[:alnum:] ]') from testx;

The select will return 0 if string contains only alphanumeric or spaces, else > 0.

So, you can add a where clause to grab just the "bad" strings:

select val1 from testx where regexp_instr(val1, '[^[:alnum:] ]') > 0;

Of course you can modify this as needed depending on your definition of "special characters".

EDIT: if you don't care about flagging punctuation, try:

select val1 from testx where regexp_instr(val1, '[^[:alnum:] [:punct:]]') > 0;

again, modify as needed to your definition

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.