validate Registration Credentials via Regex and validation logics - Android java.util.regex

Android examples for java.util.regex:Password Pattern

Description

validate Registration Credentials via Regex and validation logics

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern EMAIL_ADDRESS_PATTERN = Pattern
            .compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
                    + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
                    + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");

    public static String[] validateRegistrationCredentials(String username,
            String password, String confirmPassword, String email,
            String confirmEmail, String securityAnswer) {
        List<String> errors = new ArrayList<>();
        if (username.isEmpty()) {
            errors.add("Must provide username.\n");
        }//from   w  w w  . ja v a 2 s . c  o m
        if (password.isEmpty()) {
            errors.add("Must provide password.\n");
        }
        if (confirmPassword.isEmpty()) {
            errors.add("Must provide confirmation password.\n");
        }
        if (email.isEmpty()) {
            errors.add("Must provide email.\n");
        }
        if (confirmEmail.isEmpty()) {
            errors.add("Must provide confirmation email.\n");
        }
        if (securityAnswer.isEmpty()) {
            errors.add("Must provide security answer.\n");
        }
        if (!password.equals(confirmPassword)) {
            errors.add("Passwords do not match");
        }
        if (!email.equals(confirmEmail)) {
            errors.add("Emails do not match");
        }
        if (!validateEmail(email)) {
            errors.add("Invalid email address");
        }
        if (errors.size() > 0) {
            return errors.toArray(new String[errors.size()]);
        }
        return new String[0];
    }

    public static boolean validateEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
}

Related Tutorials