jQuery validation error message positioning is odd - javascript

I am currently using jQuery validation plugin to validate my form field. When a user did not enter any value on the field, an error label will be displayed, stating that "this field is required". However, the error label is displayed all the way at the left side of the browser which seems odd. Here is a screenshot of my problem, the desired outcome and my codes
Error screenshot
Desired outcome
<script>
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function (element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function (element) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
}
});
$('#dataForm').validate({
rules: {
accountNameInput: {
required: true
}
}
});
</script>
<form id="dataForm" role="form" class="form-horizontal">
<div class="form-group col-md-12">
<label class="control-label col-md-4" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" class="form-control font-bold"
maxlength="100" placeholder="Account name" value="" />
</div>
</form>

Related

Jquery validation skipping invalid input

I'm moving my HTML/JS over to Django and using it's validation forms. However, I still want to use Jquery's for certain things like making sure an answer is inputted before the div is hidden. Jquery validate used to work but I broke it transitioning to Django, possibly from using the input tags to create my inputs? I use an onclick to validate instead of submit by the way.
Anyway, here is the JS:
$(document).ready(function() {
var validater = $("#cc_form").validate({
rules: {
pt_cc : {
required: true,
minlength: 3,
},
},
messages: {
pt_cc: "Please enter an answer",
},
errorPlacement: function(error, element) {
if (element.attr("name") == "pt_cc") {
error.appendTo("#cc_error")}
else {
error.insertAfter(element);}},
onfocusout: false,
invalidHandler: function(form, validater) {
var errors = validater.numberOfInvalids();
if (errors) {
validater.errorList[0].element.focus();}
}});});
function sendto() {
if ($("#cc_form").valid()) {
console.log('valid');}
else {return false};}
And the rendered HTML, after Django does its thing:
<form id='cc_form' name="contentForm" role="form" data-toggle="validator">
<div style='display:none; background-color:white' class="jumbotron shadow-lg text-center mb-4 mx-5" id=somethingelse_page>
<h3>In 5 words or so, try to describe your problem.</h3><hr>
<div class="d-flex align-items-center mx-auto input-group mb-2">
<div class="input-group mb-2 col-md-6 mx-auto">
<input type="text" name="pt_cc" placeholder="For example: "I can't sleeep at all"" class="form-control" id="something_else_cc_answer" maxlength="75" required="">
</div>
</div>
<div id='sub_1' class='row'>
<input id='sub_but_1' type="button" class="btn btn-primary d-flex align-items-center px-4 mx-auto my-3" value='Next' onclick='sendto()'>
</div>
</form>
</div>
Every time time I click that button, the console prints "valid" and moves on. I don't understand how the form passes as valid without anything in the input field.
Also maybe of note, when inspecting the element, the field required at the end of the input appears without an = or "", this came over on coping the element to paste here.
here you can observed my code
$("#employeeContactForm").validate({
rules: {
cellular_number: "required",
address_1: "required"
},
messages: {
cellular_number: "No Handphone wajib dipilih (*)",
address_1: "Alamat sesuai KTP wajib diisi",
},
errorElement: "em",
errorPlacement: function(error, element) {
return errorPlacement(error, element)
},
highlight: function(element, errorClass, validClass) {
return highlight(element, errorClass, validClass);
},
unhighlight: function(element, errorClass, validClass) {
return unhighlight(element, errorClass, validClass);
},
submitHandler: function(form) {
$(form).ajaxSubmit({
success: function() {
$("#employeeContactForm").addClass('submited');
}
});
},
});
var isValid = $("#employeeContactForm").valid();
if(isValid){console.log("valid")}
i wonder why either janggo or you using <input> for button instead <button>
<input id='sub_but_1' type="button" class="btn btn-primary d-flex align-items-center px-4 mx-auto my-3" value='Next' onclick='sendto()'>
extra
<input type="text" name="pt_cc" placeholder="For example: "I can't sleeep at all"" class="form-control" id="something_else_cc_answer" maxlength="75" required="">
you don't need required="" on the html section because you already defined it on the jquery validator. and also you can move maxlength from the html to jquery validator rules.
Follow up:
The problem was I was using a form within a form. This had worked for some reason in my original code by an act of god. This is the docs explaing form within form problems: http://www.w3.org/MarkUp/html3/forms.html
To solve this issue:
Embed an HTML <form> within a larger <form>?

jQuery validation remove error message instead of display: none

I have the basic usage of jQuery validation:
<div class="form__group form__group--floating-labels">
<label for="registrationFirstname">{{__('Name')}} *</label>
<input type="text" name="first_name" class="input input--text fullwidth" id="registrationFirstname" required />
</div>
With the error placement:
errorElement: 'div',
errorPlacement: function (error, element) {
$(error).addClass('registration__validation-error');
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertBefore($(element).parent('.form__group--floating-labels'));
}
}
It works the way that I submit the form, if it is has the error, the message shows up, I fill up the field and the error message gets display:none.
What I would need is - remove the div with the error message completely, not just hide it. Is it possible?

How to add different classes to my validate() elements in jQuery?

I'm using the validate jQuery method to validate this form:
<form id="emailRecover">
<div class="row light-field-container error-container">
<input type="text" id="dniPassword" name="dniPassword" required="" class="form-text">
<span class="tool-error">Please, insert your ID card number.</span>
<div class="birthdate-input">
<input type="text" id="birthdatePassword" required="" name="birthdatePassword" class="form-text">
<span class="format">DD/MM/AA</span>
</div>
<span class="tool-error">Please, insert your birth date.</span>
<input type="button" id="sendword-new-button" name="send_password_new_button" >
</div>
</form>
And I created the following validate() method for it:
$('#emailRecover').validate({
errorPlacement: function () { },
errorClass: 'form-text form-error',
errorElement: 'span',
errorElementClass: 'tool-error',
rules: {
dniPassword: {
required: true
},
birthdatePassword: {
required: true
}
}
});
I want to add a custom class to my error inputs, something like this:
<form id="emailRecover">
<div class="row light-field-container error-container">
<input type="text" id="dniPassword" name="dniPassword" required="" class="form-text form-error"> <-- Added class to this input
<span class="tool-error">Please, insert your ID card number.</span>
<div class="birthdate-input">
<input type="text" id="birthdatePassword" required="" name="birthdatePassword" class="form-text form-error"> <-- Added class to this input
<span class="format">DD/MM/AA</span>
</div>
<span class="tool-error">Please, insert your birth date.</span>
<input type="button" id="sendword-new-button" name="send_password_new_button" >
</div>
</form>
But if I set my *errorClass: form-text form-error", then the labels and the spans also have this class, and then my styles are not applied.
How can I add my custom class only to the input field?
As an addition to the accepted answer, I could unhighlight the focused element by adding this to my validation rule:
unhighlight: function (element, errorClass, validClass) {
$(element.form).find('input[name='+$(':focus').attr('name')+']').removeClass("form-error");
},
You can define highlight and unhighlight properties like this:
$('form').validate({
// make sure error message isn't displayed
errorPlacement: function () { },
// set the errorClass as a random string to prevent input disappearing when valid
errorClass : "error_class_name",
// use highlight and unhighlight
highlight: function (element, errorClass, validClass) {
$(element.form).find("input").addClass("error");
},
unhighlight: function (element, errorClass, validClass) {
$(element.form).find("input").removeClass("error");
}
});
highlight - How to highlight invalid fields. Override to decide which fields and how to highlight.
unhighlight - Called to revert changes made by option highlight, same arguments as highlight.
Hope this helps!

Unable to validate bootstrap

I have the following jquery code
$().ready(function){
$("#Form").validate({
rules:{
DL:{
minlength:2
}
}
});
}
message:{
DL:{
minlength:"DL should be of at least 5";
}
}
The validation required is that the field DL should have length of 5.
The html code is below
<div class="form-group">
<label for="exampleInputText">Driving License Number</label><input
type="text" class="form-control" id="DL" required>
</div>
But the page does not seem to validate, after clicking a button, instead of showing message the page just scrolls upwards.
Here is your solution
https://jsfiddle.net/geradrum/far1fj1n/
All the code have syntax errors.
And the $() should be $(document)
The main problem is that the rules object looks for the element's name and you were using the id of the element.
index.html
<form id="FORM">
<div class="form-group">
<label for="exampleInputText">Driving License Number</label><input type="text" class="form-control" name="DL" required>
</div>
<input type="submit" value="Validate!">
</form>
app.js
$(document).ready(function(){
$( "#FORM" ).validate({
rules: {
DL: {
required: true,
minlength: 5
}
},
messages: {
DL: "DL should be of at least 5"
}
});
});

jQuery validation plugin submits even if validation errors occur

I am trying to validate a bootstrap form with jQuery.
var formSubmit = $("#dl-mg-form-publish").validate({
rules: {
'dl-mg-input-youtube': {
required: true,
url:true,
},
'dl-mg-input-title': {
required: true,
minlength: 6 });
I am trying to validate this:
var videoInformation = {
youtubeID: $('#dl-mg-input-youtube').val(),
title: $('#dl-mg-input-title').val(), }
This is my html:
<form class="form-horizontal dl-mg-form-horizontal" id="dl-mg-form-publish" action="#">
<div class="form-group">
<label for="dl-mg-input-youtube" class="control-label col-xs-2">YouTube Video ID:</label>
<div class="col-xs-6">
<input type="url" class="form-control" id="dl-mg-input-youtube" name="dl-mg-input-youtube" placeholder="Youtube ID">
</div>
</div>
<div class="form-group">
<label for="dl-mg-input-title" class="control-label col-xs-2">Video Title:</label>
<div class="col-xs-6">
<input type="text" class="form-control" id="dl-mg-input-title" name="dl-mg-input-title" placeholder="Video Title">
</div>
</div>
I am new at programming I don't know how to validate first and then submit. I tried using a .click handler but it submits the fields with errors anyway. Please help!
Before submitting your form you need to validate the form. You can do this inside the click event like:
$("#target").click(function () {
// Validate the form first
if (!$("#dl-mg-form-publish").valid()) return false;
// Your form is valid, so continue with you submit logic..
});
More info here: .valid()
EDIT:
Disable auto validation on keypress
Use this options for the validate() method:
$("#dl-mg-form-publish").validate({
onfocusout: false,
onkeyup: false,
// other options here
})

Categories

Resources