Merge pull request #158 from Doha2012/master

add form validation
This commit is contained in:
Eugen 2015-03-09 14:03:40 +02:00
commit 42448fc464
5 changed files with 371 additions and 23 deletions

View File

@ -9,6 +9,7 @@ import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
@ -17,6 +18,7 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
@ -179,7 +181,45 @@ public class JavaReaderToXUnitTest {
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = IOUtils.toInputStream(initialReader.toString());
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
initialReader.close();
targetStream.close();
}
// tests - Reader to InputStream with encoding
@Test
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
final Reader initialReader = new StringReader("With Java");
final char[] charBuffer = new char[8 * 1024];
final StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
builder.append(charBuffer, 0, numCharsRead);
}
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8));
initialReader.close();
targetStream.close();
}
@Test
public void givenUsingGuava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
final Reader initialReader = new StringReader("With Guava");
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes(Charsets.UTF_8));
initialReader.close();
targetStream.close();
}
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
final Reader initialReader = new StringReader("With Commons IO");
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
initialReader.close();
targetStream.close();

View File

@ -7,6 +7,7 @@
<link rel="stylesheet" href="<c:url value="/resources/datetime-picker.css" />">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="<c:url value="/resources/datetime-picker.js" />"></script>
<script src="<c:url value="/resources/validator.js" />"></script>
</head>
<body>
@ -20,7 +21,7 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="info">Schedule to Reddit</a>
<a class="navbar-brand" href="<c:url value="/info" />">Schedule to Reddit</a>
</div>
<p class="navbar-text navbar-right">Logged in as <b><c:out value="${username}"/></b>&nbsp;&nbsp;&nbsp;</p>
@ -28,9 +29,9 @@
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="posts">My Scheduled Posts</a></li>
<li><a href="post">Post to Reddit</a></li>
<li><a href="postSchedule">Schedule Post to Reddit</a></li>
<li><a href="<c:url value="/posts" />">My Scheduled Posts</a></li>
<li><a href="<c:url value="/post" />">Post to Reddit</a></li>
<li><a href="<c:url value="/postSchedule" />">Schedule Post to Reddit</a></li>
</ul>
</div><!-- /.navbar-collapse -->
@ -38,31 +39,31 @@
</nav>
<div class="container">
<h1>Edit Scheduled Post</h1>
<form action="<c:url value="/updatePost/${post.getId()}" />" method="post">
<form action="<c:url value="/updatePost/${post.getId()}" />" method="post" role="form" data-toggle="validator">
<div class="row">
<input type="hidden" name="id" value="${post.getId()}"/>
<div class="form-group">
<label class="col-sm-3">Title</label>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" value="${post.getTitle()}" required/></span>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" value="${post.getTitle()}" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Url</label>
<span class="col-sm-9"><input name="url" placeholder="url" class="form-control" value="${post.getUrl()}" required/></span>
<span class="col-sm-9"><input name="url" type="url" placeholder="url" class="form-control" value="${post.getUrl()}" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Subreddit</label>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit" class="form-control" value="${post.getSubreddit()}" required/></span>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit" class="form-control" value="${post.getSubreddit()}" required data-minlength="3"/></span>
</div>
<br><br>
<div class="col-sm-3">
<input type="checkbox" name="sendreplies" value="true" <c:if test="${post.isSendReplies()=='true'}"> checked </c:if> /> Send replies to my inbox
<label>Send replies to my inbox</label> &nbsp; <input type="checkbox" name="sendreplies" value="true" <c:if test="${post.isSendReplies()=='true'}"> checked </c:if> />
</div>
<br><br>
<label class="col-sm-3">Submission Date</label>
<span class="col-sm-9"><input type="text" name="date" class="form-control" value="${dateValue}"></span>
<span class="col-sm-9"><input type="text" name="date" class="form-control" value="${dateValue}" readonly></span>
<script type="text/javascript">
$(function(){
$('*[name=date]').appendDtpicker({"inline": true});

View File

@ -7,6 +7,7 @@
<link rel="stylesheet" href="<c:url value="/resources/datetime-picker.css" />">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="<c:url value="/resources/datetime-picker.js" />"></script>
<script src="<c:url value="/resources/validator.js" />"></script>
</head>
<body>
@ -38,30 +39,30 @@
</nav>
<div class="container">
<h1>Schedule Post to Reddit</h1>
<form action="schedule" method="post">
<form action="schedule" method="post" role="form" data-toggle="validator">
<div class="row">
<div class="form-group">
<label class="col-sm-3">Title</label>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" required/></span>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Url</label>
<span class="col-sm-9"><input name="url" placeholder="url" class="form-control" required/></span>
<span class="col-sm-9"><input name="url" type="url" placeholder="url" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Subreddit</label>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit" class="form-control" required/></span>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit (e.g. kitten)" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="col-sm-3">
<input type="checkbox" name="sendreplies" value="true"/> Send replies to my inbox
<label>Send replies to my inbox</label> &nbsp;<input type="checkbox" name="sendreplies" value="true"/>
</div>
<br><br>
<label class="col-sm-3">Submission Date</label>
<span class="col-sm-9"><input type="text" name="date" class="form-control"></span>
<span class="col-sm-9"><input type="text" name="date" class="form-control" readonly></span>
<script type="text/javascript">
$(function(){
$('*[name=date]').appendDtpicker({"inline": true});

View File

@ -4,6 +4,8 @@
<title>Schedule to Reddit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="<c:url value="/resources/validator.js" />"></script>
</head>
<body>
@ -35,25 +37,25 @@
</nav>
<div class="container">
<h1>Post to Reddit</h1>
<form action="submit" method="post">
<form action="submit" method="post" role="form" data-toggle="validator">
<div class="row">
<div class="form-group">
<label class="col-sm-3">Title</label>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" required/></span>
<span class="col-sm-9"><input name="title" placeholder="title" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Url</label>
<span class="col-sm-9"><input name="url" placeholder="url" class="form-control" required /></span>
<span class="col-sm-9"><input name="url" type="url" placeholder="url" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="form-group">
<label class="col-sm-3">Subreddit</label>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit" class="form-control" required/></span>
<span class="col-sm-9"><input name="sr" placeholder="Subreddit (e.g. kitten)" class="form-control" required data-minlength="3"/></span>
</div>
<br><br>
<div class="col-sm-3">
<input type="checkbox" name="sendreplies" value="true"/> Send replies to my inbox
<label>Send replies to my inbox</label> &nbsp;<input type="checkbox" name="sendreplies" value="true"/>
</div>
<br><br>
@ -68,7 +70,7 @@
<img src="http://www.reddit.com/captcha/${iden}" alt="captcha" width="200"/>
</c:if>
<br><br>
<button type="submit" class="btn btn-primary">Post</button>
<span class="col-sm-3"><button type="submit" class="btn btn-primary">Post</button></span>
</div>
</form>
</div>

View File

@ -0,0 +1,304 @@
/* ========================================================================
* Bootstrap (plugin): validator.js v0.7.2
* ========================================================================
* The MIT License (MIT)
*
* Copyright (c) 2013 Cina Saffary.
* Made by @1000hz in the style of Bootstrap 3 era @fat
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ======================================================================== */
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
var Validator = function (element, options) {
this.$element = $(element)
this.options = options
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
$this.val() && $this.trigger('input.bs.validator')
})
})
}
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
errors: {
match: 'Does not match',
minlength: 'Not long enough'
}
}
Validator.VALIDATORS = {
native: function ($el) {
var el = $el[0]
return el.checkValidity ? el.checkValidity() : true
},
match: function ($el) {
var target = $el.data('match')
return !$el.val() || $el.val() === $(target).val()
},
minlength: function ($el) {
var minlength = $el.data('minlength')
return !$el.val() || $el.val().length >= minlength
}
}
Validator.prototype.validateInput = function (e) {
var $el = $(e.target)
var prevErrors = $el.data('bs.validator.errors')
var errors
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
var self = this
this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length ? self.showErrors($el) : self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var validators = [Validator.VALIDATORS.native]
var deferred = $.Deferred()
var options = this.options
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
$.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
var error = getErrorMessage(key)
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && $el.val() && $el.data('remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = $el.val()
$.get($el.data('remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var delay = this.options.delay
this.options.delay = 0
this.$element.find(':input').trigger('input.bs.validator')
this.options.delay = delay
return this
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
var errors = $el.data('bs.validator.errors')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.removeClass('has-success')
$group.addClass('has-error')
$feedback.removeClass('glyphicon-ok')
$feedback.addClass('glyphicon-warning-sign')
})
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error')
$group.addClass('has-success')
$feedback.removeClass('glyphicon-warning-sign')
$feedback.addClass('glyphicon-ok')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$element.find(':input:enabled').filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
return this.type === 'checkbox' ? !this.checked :
this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
$.trim(this.value) === ''
}
return !!this.$element.find(':input[required]:enabled').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if(!this.options.disable) return
var $btn = this.$element.find('input[type="submit"], button[type="submit"]')
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
.css({'pointer-events': 'all', 'cursor': 'pointer'})
}
Validator.prototype.defer = function ($el, callback) {
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.destroy = function () {
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$element.find(':input')
.off('.bs.validator')
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors').each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
this.$element.find('.has-error').removeClass('has-error')
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);