net.prasenjit.auth.validation.StrongPasswordValidator.java Source code

Java tutorial

Introduction

Here is the source code for net.prasenjit.auth.validation.StrongPasswordValidator.java

Source

/*
 * Copyright (c) 2016 Prasenjit Purohit
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package net.prasenjit.auth.validation;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by PRASENJIT-NET on 5/3/2016.
 *
 * @author PRASEN
 * @version $Id: $Id
 */
public class StrongPasswordValidator implements ConstraintValidator<StrongPassword, String> {
    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(StrongPassword constraintAnnotation) {
    }

    /** {@inheritDoc} */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringUtils.hasText(value))
            return true;
        int upperCount = 0;
        int specialCount = 0;
        int lowerCount = 0;
        int numericCount = 0;
        for (int i = 0; i < value.length(); i++) {
            char current = value.charAt(i);
            if (Character.isDigit(current))
                numericCount = 1;
            if (Character.isUpperCase(current))
                upperCount = 1;
            if (Character.isLowerCase(current))
                lowerCount = 1;
            if (!Character.isLetterOrDigit(current))
                specialCount = 1;
        }
        return upperCount + lowerCount + numericCount + specialCount >= 2;
    }
}