@Ronny noget i den her stil måske:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>demo</title>
- <link href="style.css" type="text/css" rel="Stylesheet">
- </head>
- <body>
- <form class="" action="" method="post">
- <fieldset>
- <label>Brugernavn:</label>
- <input type="text" name="username" data-validate="empty" value="">
- </fieldset>
-
- <fieldset>
- <label>E-mail:</label>
- <input type="text" name="email" data-validate="empty email" value="">
- </fieldset>
-
- <fieldset>
- <button type="submit" name="button">Afsend</button>
- </fieldset>
- </form>
-
- <script>
- ;(function() {
-
-
- function showMsg(msg) {
- var parent = this.parentNode,
- oldMsg = parent.querySelector('.message');
-
-
- if ( oldMsg !== null ) {
- parent.removeChild(oldMsg);
- }
-
- var span = document.createElement('span'),
- txt = document.createTextNode(msg.message);
-
- span.classList.add(msg.cls);
- span.classList.add('message');
-
- span.appendChild(txt);
- parent.appendChild(span);
- }
-
-
- function validate(event) {
- var checks = this.getAttribute('data-validate'),
- errors = false,
- self = this;
-
- if ( !checks ) {
- return;
- }
-
- checks.split(" ").forEach(function(item, i){
- if ( !validators.hasOwnProperty(item) ) {
- return;
- }
-
- if ( !validators[item].call(self) ) {
- errors = true;
- }
- });
-
- var message = (errors)
- ? { 'cls' : 'error', 'message' : 'Forkert' }
- : { 'cls' : 'ok', 'message' : 'Ok' };
-
- is_valid = !errors;
-
- showMsg.call(this, message);
- }
-
- var is_valid = false,
- validators = {
- email : function() {
- return this.value.indexOf('@') > -1;
- },
-
- empty : function () {
- return this.value.length;
- }
- },
- elements = document.querySelectorAll('form input');
-
-
- Array.prototype.forEach.call(elements, function(el, i){
- el.addEventListener('input', validate.bind(el), false);
- });
-
- document.querySelector("form").addEventListener('submit', function(event) {
- if ( !is_valid ) {
- event.preventDefault();
- event.stopPropagation();
- }
- }, false);
- })();
- </script>
- </body>
- </html>
Indlæg senest redigeret d. 31.03.2016 22:33 af Bruger #17081