0

I have question about validation form in js, could you help me because I stuck. I would like separate click in question input and in tag input. But now if I click in tag input show information from question input (information on red background). I think I have problems in my js code.

var validateForm = (function() {

  var options = {};
  var classError = 'error';
  var showFieldValidation = function(input, inputIsValid) {
    if (!inputIsValid) {
      if (!input.parentNode.className || input.parentNode.className.indexOf(options.classError) == -1) {
        input.parentNode.className += ' ' + options.classError
        var d = document.getElementById("de_scri_tit_11")
        d.classList.add("w_te_88")
        $(document).ready(function() {
          $("#de_scri_tit_11").css('display', 'block')

        });
      }
    } else {
      var regError = new RegExp('(\\s|^)' + options.classError + '(\\s|$)');
      input.parentNode.className = input.parentNode.className.replace(regError, '');
      var d = document.getElementById("de_scri_tit_11")
      d.classList.remove("w_te_88")
      $(document).ready(function() {
        $("#de_scri_tit_11").css('display', 'none')

      });
    }
  };

  var testInputText = function(input) {
    var fieldHasError = false;
    var mailReg = new RegExp('^[0-9a-zA-Z_.-]', 'gi');

    if (!mailReg.test(input.value)) {
      showFieldValidation(input, false);
      return false;
    } else {
      showFieldValidation(input, true);
      return true;
    }
  };



  var prepareElements = function() {
    var elements = options.form.getElementsByClassName('til_l67_text');

    [].forEach.call(elements, function(element) {
      element.removeAttribute('required');
      element.className += ' required';

      if (element.nodeName.toUpperCase() == 'INPUT') {
        var type = element.type.toUpperCase();

        if (type == 'TEXT') {
          element.addEventListener('keyup', function() {
            testInputText(element)
          });
          element.addEventListener('blur', function() {
            testInputText(element)
          });
        }

      }

    });
  };

  var prepareElementsTag = function() {
    var elements = options.form.getElementsByClassName('as_tags_in_l67');

    [].forEach.call(elements, function(element) {
      element.removeAttribute('required');
      element.className += ' required';

      if (element.nodeName.toUpperCase() == 'INPUT') {
        var type = element.type.toUpperCase();

        if (type == 'TEXT') {
          element.addEventListener('keyup', function() {
            testInputText(element)
          });
          element.addEventListener('blur', function() {
            testInputText(element)
          });
        }

      }

    });
  };

  var formSubmit = function() {
    options.form.addEventListener('submit', function(e) {
      e.preventDefault();

      var validated = true;
      var elements = options.form.querySelectorAll('.required');

      [].forEach.call(elements, function(element) {
        if (element.nodeName.toUpperCase() == 'INPUT') {
          var type = element.type.toUpperCase()

          if (type == 'TEXT') {
            if (!testInputText(element)) validated = false;
          }

        }
      });

      if (validated) {
        this.submit();
      } else {
        return false;
      }
    });
  };

  var init = function(_options) {

    options = {
      form: _options.form || null,
      classError: _options.classError || 'error'

    }
    if (options.form == null || options.form == undefined || options.form.length == 0) {
      console.warn('validateForm: Źle przekazany formularz');
      return false;
    }
    prepareElements();
    prepareElementsTag()
    formSubmit();
  };

  return {
    init: init
  }
})();

document.addEventListener("DOMContentLoaded", function() {
  var form = document.querySelector('.form');
  validateForm.init({
    form: form
  })
});
#de_scri_tit_11 {
  height: 50px;
  font-size: 14px;
  width: 240px;
  position: absolute;
  left: 350px;
  top: 3px;
  color: #fff;
  font-family: Arial;
  display: none;
  background-color: #DB083E;
  border-radius: 8px;
  padding: 5px;
  border: 3px solid #666;
  font-weight: bold;
}
.w_te_88:before {
  content: 'title should have min 15 characters'
}
#de_scri_tag_11 {
  height: 50px;
  font-size: 14px;
  width: 240px;
  position: absolute;
  left: 860px;
  top: 233px;
  color: #fff;
  font-family: Arial;
  display: none;
  background-color: #DB083E;
  border-radius: 8px;
  padding: 5px;
  border: 3px solid #666;
  font-weight: bold;
}
.w_tg_11:before {
  content: 'Tytuł musi mieć minium 15 znaków i maksimum 100 znaków'
}
.form .error input[type=text] {
  color: #DB083E;
  border-color: #DB083E;
  background: #FFEDED url(img/error.png) right center no-repeat;
  background-position: calc(100% - 10px) center;
  box-shadow: 0 0 2px 2px red;
}
#til_bo_x43 {
  width: 370px;
  height: 40px;
  padding-top: 5px;
  position: absolute;
  top: 20px;
  left: 10px;
}
label.til_l67 {
  font-size: 16px;
  font-family: Arial;
  font-weight: bold;
}
input[type=text].til_l67_text {
  margin-left: 19px;
  width: 203px;
  font-size: 16px;
  font-family: Arial;
  height: 30px;
  border: 1px solid #33b2ff;
  padding-left: 5px;
}
input[type=text].til_l67_text:focus {
  outline-style: none;
}
.as_tags_cho99 {
  width: 325px;
  height: 40px;
  padding-top: 5px;
  position: relative;
  top: 70px;
  left: 75px;
}
label.as_tags_lab_l67 {
  font-size: 16px;
  font-family: Arial;
  font-weight: bold;
}
input[type=text].as_tags_in_l67 {
  margin-left: 19px;
  width: 193px;
  font-size: 16px;
  font-family: Arial;
  height: 30px;
  border: 1px solid #33b2ff;
  padding-left: 5px;
}
input[type=text].as_tags_in_l67:focus {
  outline-style: none;
}
.post_ans_976 {
  position: relative;
  left: 170px;
  top: 100px;
  height: 32px;
  width: 150px;
  font-size: 17px;
  background-color: #ff9c33;
  color: #fff;
  font-family: Arial;
  border: none;
  border-radius: 7px;
  margin-bottom: 200px;
}
.post_ans_976:focus {
  background-color: #ff9c33;
}
.post_ans_976:active {
  background-color: #ff4c00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
  <div class="ask_con_area67">

    <div id="til_bo_x43">
      <label class="til_l67">Tytuł pytania</label>
      <input class="til_l67_text" type="text" placeholder="Question title" autocomplete="off" required />
      <div id="de_scri_tit_11"></div>
    </div>

    <div class="as_tags_cho99">
      <label class="as_tags_lab_l67">Tagi</label>
      <input class="as_tags_in_l67" type="text" placeholder="Question tags" required />
      <div id="de_scri_tag_11"></div>
    </div>
    <button class="post_ans_976">Add question</button>
  </div>
</form>

1 Answer 1

1

This behaviour is happening since you have added the validation code on the blur event

 element.addEventListener('keyup', function() {testInputText(element)});
 element.addEventListener('blur', function() {testInputText(element)});

Change it to focus to get the desired result.

element.addEventListener('keyup', function() {testInputText(element)});
element.addEventListener('focus', function() {testInputText(element)});

Edit: as per the discussion in comment section

var validateForm = (function() {
	
    var options = {};
    var classError = 'error';
	

	
    var showFieldValidation = function(input, inputIsValid) {
        if (!inputIsValid) {
            if (!input.parentNode.className || input.parentNode.className.indexOf(options.classError)==-1) {
            input.parentNode.className += ' ' + options.classError
			
              
            if(input.classList.contains("til_l67_text"))
            {
               var d = document.getElementById("de_scri_tit_11");
			   d.classList.add("w_te_title")
               $("#de_scri_tit_11").css('display','block')
            }
            else{
            var d = document.getElementById("de_scri_tag_11");
            d.classList.add("w_te_tag");
            $("#de_scri_tag_11").css('display','block')
            }
			
				
						
            }
        } else {
            var regError = new RegExp('(\\s|^)'+options.classError+'(\\s|$)');
            input.parentNode.className = input.parentNode.className.replace(regError, '');
          
            if(input.classList.contains("til_l67_text"))
            {
			    var d = document.getElementById("de_scri_tit_11");
                d.classList.remove("w_te_title");
                $("#de_scri_tit_11").css('display','none');
            }
            else{
                var d = document.getElementById("de_scri_tag_11");
                d.classList.remove("w_te_tag");
                $("#de_scri_tag_11").css('display','none');
            }
              
        }
    };
		
     var testInputText = function(input) {
        var fieldHasError = false;
        var mailReg = new RegExp('^[0-9a-zA-Z_.-]', 'gi');
       
        if (!mailReg.test(input.value)) {
            showFieldValidation(input, false);
            return false;
        } else {
            showFieldValidation(input, true);
            return true;
        }    
    };
	
	
		
    var prepareElements = function() {
        var elements = options.form.getElementsByClassName('til_l67_text');

        [].forEach.call(elements, function(element) {
            element.removeAttribute('required');
            element.className += ' required';

            if (element.nodeName.toUpperCase() == 'INPUT') {
                var type = element.type.toUpperCase();

                if (type == 'TEXT') {
                   
                    element.addEventListener('blur', function() {testInputText(element)});
                }
             
            }
           
        });        
    };
	
	 var prepareElementsTag = function() {
        var elements = options.form.getElementsByClassName('as_tags_in_l67');

        [].forEach.call(elements, function(element) {
            element.removeAttribute('required');
            element.className += ' required';

            if (element.nodeName.toUpperCase() == 'INPUT') {
                var type = element.type.toUpperCase();

                if (type == 'TEXT') {
                  
                    element.addEventListener('blur', function() {testInputText(element)});
                }
             
            }
          
        });        
    };
	
	
	
	
	
	
	
	
	
	
	
	
var formSubmit = function() {
    options.form.addEventListener('submit', function(e) {
        e.preventDefault();
    
        var validated = true;
    
      
        var elements = options.form.querySelectorAll('.required');

        
        [].forEach.call(elements, function(element) {
            if (element.nodeName.toUpperCase() == 'INPUT') {
                var type = element.type.toUpperCase()
                             
                if (type == 'TEXT') {
                    if (!testInputText(element)) validated = false;
                }  
				 
            }
        });
                    
        if (validated) {
            this.submit();
        } else {
            return false;
        }
    });    
};
   	
    var init = function(_options) {
        
        options = {
            form : _options.form || null,
            classError : _options.classError || 'error'
			
        }
        if (options.form == null || options.form == undefined || options.form.length==0) {
            console.warn('validateForm: Źle przekazany formularz');
            return false;
        }
        prepareElements();
		prepareElementsTag()
		formSubmit();
	};

    return {
        init : init
    }
})();

document.addEventListener("DOMContentLoaded", function() {
    var form = document.querySelector('.form');
    validateForm.init({form : form})
});
#de_scri_tit_11
{
	height: 30px;
	font-size:14px;
	width:240px;
	position:absolute;
	left:350px;
	top:3px;
	color:#fff;
	font-family:Arial;
	display:none;
	background-color:#DB083E;
	border-radius:8px;
	padding:5px;
	border:3px solid #666;
	font-weight:bold;
}
.w_te_title:before
{
	content:'Title should have min 15 characters'
}
.w_te_tag:before
{
	content:'Tag should have min 15 characters'
}
#de_scri_tag_11
{
	height: 30px;
    position: relative;
    font-size: 14px;
    width: 240px;
    left: 275px;
    top: -36px;
    color: #fff;
    font-family: Arial;
    display: none;
    background-color: #DB083E;
    border-radius: 8px;
    padding: 5px;
    border: 3px solid #666;
    font-weight: bold;
}
.w_tg_11:before
{
	content:'Tytuł musi mieć minium 15 znaków i maksimum 100 znaków'
}
.form .error input[type=text]{
    color: #DB083E;
    border-color: #DB083E;
    background: #FFEDED url(img/error.png) right center no-repeat;
    background-position: calc(100% - 10px) center;
	box-shadow: 0 0 2px 2px red;	
  }

#til_bo_x43
{
	width:370px;
	height:40px;
	padding-top:5px;
	position:absolute;
	top:20px;
	left:10px;

}
label.til_l67
{
	font-size:16px;
	font-family:Arial;
	font-weight:bold;
}
input[type=text].til_l67_text
{
	margin-left:19px;
	width:203px;
	font-size:16px;
	font-family:Arial;
	height:30px;
	border:1px solid #33b2ff;
	padding-left:5px;
}
input[type=text].til_l67_text:focus
{
	outline-style:none;
}

.as_tags_cho99
{
	width:325px;
	height:40px;
	padding-top:5px;
	position:relative;
	top:70px;
	left:75px;

}
label.as_tags_lab_l67
{
	font-size:16px;
	font-family:Arial;
	font-weight:bold;
}
input[type=text].as_tags_in_l67
{
	margin-left:19px;
	width:193px;
	font-size:16px;
	font-family:Arial;
	height:30px;
	border:1px solid #33b2ff;
	padding-left:5px;
}
input[type=text].as_tags_in_l67:focus
{
	outline-style:none;
}
.post_ans_976
{
	position:relative;
	left:170px;
	top:100px;
	height:32px;
	width:150px;
	font-size:17px;
	background-color:#ff9c33;
	color:#fff;
	font-family:Arial;
	border:none;
	border-radius:7px;
	margin-bottom:200px;
}
.post_ans_976:focus
{
	background-color:#ff9c33;
}
.post_ans_976:active
{
	background-color:#ff4c00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form">
	<div class="ask_con_area67">
		
		<div id="til_bo_x43">
			<label class="til_l67">Tytuł pytania</label>
			<input class="til_l67_text" type="text" placeholder="Question title" autocomplete="off" required />
			<div id="de_scri_tit_11"></div>
		</div>
				
		<div class="as_tags_cho99">
			<label class="as_tags_lab_l67">Tagi</label>
			<input class="as_tags_in_l67" type="text" placeholder="Question tags" required />
			<div id="de_scri_tag_11"></div>
		</div>
	<button class="post_ans_976">Add question</button>	
	</div>
	
	
	</form>

Sign up to request clarification or add additional context in comments.

13 Comments

Thanks, but look when click on question input add class .w_te_88 with content css style and I would like do the same when click on tag input but can't handle with distinguish click on question input and tag input click
thaks a lot, this is big progress for me, but why invalid input is when I focus on input and no when I blur ?
because you are calling testInputText function for validation, ideally i will suggest you to do this validation on blur only because you should allow user to take an action first.
let me know in case you need more details.
aa I see, thanks. your code is perfect for me, but I would like if user focus in input, input no change but if user blur from input and inpu isw empty or no suit to pattern this red backgound will appear
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.