0

When i am trying to save a record with phone field in account object, then it has to threw an error if the value contains numerical string and null value. I can accomplish this by using validation rule

OR(ISBLANK( Phone ),NOT(ISNUMBER( Phone )))

But i want to do this by using Apex class. How can i check the phone field value if it contains numerical string and null value. I tried with following code so many times with out success. May be i was wrong with if(!Pattern.matches('[+][9][1]+[a-z]{24}+[A-Z]{24}',accs.phone))

public class Example {   

    public Account accs{get;set;}

    public Example(){
     accs = new Account();
    }

    public PageReference click() {
    if(!Pattern.matches('[+][9][1]+[a-z]{24}+[A-Z]{24}',accs.phone)){
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter correct number'));
    }
    else{
    insert accs;
    }
        return null;
    }
}

please, Can anyone explain me where i have done wrong with correct code.

Thanks in advance

KS Kumaar

0

See the below code for reference:

trigger accounttrigger on Account (before insert) {

for(account obj:trigger.new){

if(obj.phone==null || !(obj.phone.isnumeric()))

obj.adderror('phone is invalid');


}



}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.