001package org.gwtbootstrap3.client.ui.base.mixin; 002 003/* 004 * #%L 005 * GwtBootstrap3 006 * %% 007 * Copyright (C) 2013 - 2015 GwtBootstrap3 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import org.gwtbootstrap3.client.ui.form.error.ErrorHandler; 024import org.gwtbootstrap3.client.ui.form.validator.BlankValidator; 025import org.gwtbootstrap3.client.ui.form.validator.Validator; 026 027import com.google.gwt.editor.client.Editor; 028import com.google.gwt.user.client.ui.HasValue; 029import com.google.gwt.user.client.ui.Widget; 030 031/** 032 * Mixin that provides the allowBlank functionality for input fields. 033 * 034 * @param <W> the generic type 035 * @param <V> the value type 036 * 037 * @author Steven Jardine 038 */ 039public class BlankValidatorMixin<W extends Widget & HasValue<V> & Editor<V>, V> extends DefaultValidatorMixin<W, V> { 040 041 private boolean allowBlank = true; 042 043 private BlankValidator<V> blankValidator; 044 045 /** 046 * Constructor. 047 * 048 * @param inputWidget the input widget 049 * @param errorHandler the error handler 050 */ 051 public BlankValidatorMixin(W inputWidget, ErrorHandler errorHandler) { 052 super(inputWidget, errorHandler); 053 } 054 055 /** {@inheritDoc} */ 056 @Override 057 public void addValidator(Validator<V> validator) { 058 if (validator instanceof BlankValidator) { 059 allowBlank = false; 060 } 061 super.addValidator(validator); 062 } 063 064 /** 065 * Hook for custom blank validators. 066 * 067 * @return the blank validator 068 */ 069 protected BlankValidator<V> createBlankValidator() { 070 return new BlankValidator<V>(); 071 } 072 073 /** 074 * @return the allow blank 075 */ 076 public boolean getAllowBlank() { 077 return allowBlank; 078 } 079 080 /** 081 * @param allowBlank the new allow blank 082 */ 083 public void setAllowBlank(boolean allowBlank) { 084 if (blankValidator == null) { 085 blankValidator = createBlankValidator(); 086 } 087 this.allowBlank = allowBlank; 088 if (!allowBlank) { 089 addValidator(blankValidator); 090 } else { 091 removeValidator(blankValidator); 092 } 093 } 094 095}