Created
March 2, 2016 09:07
-
-
Save rtivital/ae1ef6cb529901584d14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DataValidator = (function() { | |
'use strict'; | |
var regExps = { | |
email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i, | |
url: /^((https?):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/, | |
numbers: /^\d+(\.\d{1,2})?$/, | |
digits: /[0-9]*$/, | |
letters: /[a-z][A-Z]*$/ | |
}; | |
var DataValidator = function(data) { | |
this.data = data.trim(); | |
this.length = this.data.length; | |
}; | |
DataValidator.prototype.min = function(param) { return this.length >= param; }; | |
DataValidator.prototype.max = function(param) { return this.length <= param; }; | |
DataValidator.prototype.required = function() { return this.length > 0; }; | |
DataValidator.prototype.match = function(param) { return regExps[param].test(this.data); }; | |
DataValidator.prototype.init = function(rules) { | |
var results = { data: this.data, passed: [], failed: [] }; | |
for (var rule in rules) { | |
var param = rules[rule]; | |
var config = { rule: rule, param: param }; | |
if (!this[rule](param)) { results.failed.push(config); } | |
else { results.passed.push(config); } | |
} | |
results.valid = results.failed.length === 0; | |
return results; | |
}; | |
return DataValidator; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Validator</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> | |
<link rel="stylesheet" href="styles.css"> | |
</head> | |
<body> | |
<header class="container-fluid main-header"> | |
<div class="row"> | |
<h1>Валидация данных</h1> | |
</div> | |
</header> | |
<!-- Классы в Bootsrap 3 - http://getbootstrap.com/css/#forms-control-validation --> | |
<main class="container validator-container"> | |
<div class="row"> | |
<!-- Контейнер для email адреса --> | |
<div class="col-sm-6"> | |
<div class="input-group center-block"> | |
<label for="email">Ваш адрес электронной почты</label> | |
<input type="text" class="form-control" id="email" placeholder="example@email.com"> | |
<span id="email-error-container" class="help-block">Введите адресс вашей электронной почты</span> | |
</div> | |
</div> | |
<!-- Контейнер для пароля --> | |
<div class="col-sm-6"> | |
<div class="input-group center-block"> | |
<label for="password">Ваш пароль</label> | |
<input type="password" class="form-control" id="password" placeholder="******"> | |
<span id="password-error-container" class="help-block">Введите ваш пароль</span> | |
</div> | |
</div> | |
<!-- Контейнер для кнопки, при нажатие на которую будет происходить валидация --> | |
<div class="col-sm-12"> | |
<button class="btn btn-default" id="validate" type="button">Провести валидацию</button> | |
</div> | |
</div> | |
</main> | |
<script src="DataValidator.js"></script> | |
<script src="InputValidator.js"></script> | |
<script src="scripts.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var InputValidator = (function() { | |
'use strict'; | |
var _createMessage = function(message, settings) { | |
for (var key in settings) { | |
message = message.replace('%' + key + '%', settings[key]); | |
} | |
return message; | |
}; | |
var InputValidator = function(element, settings) { | |
this.element = element; | |
this.settings = settings; | |
}; | |
InputValidator.prototype = Object.create(DataValidator.prototype); | |
InputValidator.prototype.construnctor = DataValidator; | |
InputValidator.prototype.validate = function() { | |
DataValidator.call(this, this.element.value); | |
var results = this.init(this.settings.rules); | |
if (!results.valid) { | |
var failed = results.failed[0]; | |
this.message = _createMessage(this.settings.messages[failed.rule], { | |
data: results.data, | |
rule: failed.param | |
}); | |
this.settings.onError.call(this); | |
} else { | |
this.settings.onSuccess.call(this); | |
} | |
}; | |
return InputValidator; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var onError = function() { | |
var parentNode = this.element.parentNode; | |
parentNode.classList.add('has-error'); | |
parentNode.classList.remove('has-success'); | |
parentNode.querySelector('.help-block').textContent = 'Ошибка: ' + this.message; | |
}; | |
var onSuccess = function() { | |
var parentNode = this.element.parentNode; | |
parentNode.classList.add('has-success'); | |
parentNode.classList.remove('has-error'); | |
parentNode.querySelector('.help-block').textContent = 'Ура! Всё прошло хорошо, ваши данные полность валидные.'; | |
}; | |
DataValidator.prototype.password = function() { | |
return this.data.toLowerCase() === '12345qwerty'; | |
}; | |
var emailInput = new InputValidator(document.getElementById('email'), { | |
rules: { | |
min: 5, | |
max: 20, | |
match: 'email' | |
}, | |
messages: { | |
min: 'Это поле должно содержать минимум %rule% символов. Значение %data% не подходит', | |
max: 'Это поле должно содержать максимум %rule% символов. Значение %data% не подходит', | |
match: 'Это поле должно содержать адрес электронной почты. Значение %data% не подходит' | |
}, | |
onError: onError, | |
onSuccess: onSuccess | |
}); | |
var passwordInput = new InputValidator(document.getElementById('password'), { | |
rules: { | |
required: true, | |
password: true | |
}, | |
messages: { | |
required: 'Это поле обязательно для заполнения!', | |
password: 'Пароль должет быть 12345qwerty Значение "%data%" не подходит' | |
}, | |
onError: onError, | |
onSuccess: onSuccess | |
}); | |
var validateBtn = document.getElementById('validate'); | |
validateBtn.addEventListener('click', function(e) { | |
emailInput.validate(); | |
passwordInput.validate(); | |
}, false); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.main-header { | |
background-color: #2c3e50; | |
color: #ecf0f1; | |
text-align: center; | |
padding-bottom: 1.5rem; } | |
.validator-container { | |
margin-top: 2rem; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment