Help with Jquery field validation

Asked

Viewed 26 times

-1

I did the following function for form validation in Jquery, but it got a bit big, and I have +50 fields to validate, someone knows some way to reuse this same function for the other fields without I have to copy it and change the id?

	$("#nome").blur(function(){

		var i="nome"
		var input=document.getElementById(i);
		var feed=document.getElementById("feed"+i);
		
		
		if ($(input).val().length<3) {
			$(input).addClass("erro");
			$(feed).removeClass("hide").addClass("show");
		}
			else{
				$(input).removeClass("erro").addClass("suscesso");
				$(feed).removeClass("show").addClass("hide");
			}
			
	  }) 
.suscesso{
    border-color: rgb(1, 182, 167)!important;
}

.erro{
    border-color: rgb(202, 2, 2)!important;
}
.show{
    display: block;

}
.hide{
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="nome" name="nome" required="">
      <div class="hide" id="feednome">
        Digite um nome valido
      </div>

1 answer

1

To make this function generic, you can capture the event of all input elements with the attribute 'required'. You will know which id/name to recover, because in the Callback function you will return this, which is the element that occurred the event at that time.

$("input[required]").blur(function() {
    var input = $(this),
        feed = $("#feed" + input.attr("id"));

    if(input.val().length < 3) {
        input.addClass("erro");
        feed.removeClass("hide").addClass("show");
    } else {
        $(input).removeClass("erro").addClass("sucesso");
        $(feed).removeClass("show").addClass("hide");
    }
});

I took the liberty of correcting the writing of the class "success".

I’m available, see you later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.