Search code examples
if-statementapexapex-code

salesforce apex - string must be 6 digits and numeric only


in this apex code the expected output was not getting the question is Take a string type of variable

string pincode = '500038';
  • Pincode must be exactly 6 digits, if the number of digits not equal to 6 then print "Pincode must be 6 digits"
  • Pincode must be numerics only, if user enters alphabets then show error message "Pincode must be numerics only"

I tried this code

    string pincode = '500038';
    if (pincode.isNumeric()) {
     system.debug('Pincode must be numeric only');
       if (pincode.len == 6) {
    system.debug('Pincode must be 6 digits');
}

}

Solution

  • I hope this will resolve your problem, in first condition we are checking pincode in numeric or not and in sub condition we are checking length of pincode is 6 or not and at last in else condition we will be printing the msg if pincode is not numeric. .

    string pincode = '500038';
    if (pincode.isNumeric()) {
        system.debug('Pincode is be numeric only');
        if(pincode.length() != 6) {
            system.debug('Pincode must be 6 digits');
        }
        if(pincode.length() == 6){
            system.debug('Pincode is numeric and has 6 digits::'+pincode);
        }
    }else{
        system.debug('Pincode contains other characters then number::'+pincode);
    }