Jquery validation skipping invalid input - javascript

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>?

Related

jQuery validation error message positioning is odd

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>

Show error around radio buttons

The Jquery Validation plugin docs say you can validate that at least one radio button is selected. However, when trying to do so with some extra layout, I am not getting the error highlighting.
My code looks like this.
<div class="form-group" style="margin-top:25px;">
<label for="factorSelect" class="control-label col-sm-3">Please select a recovery method</label>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-envelope"></i>
</span>
<div class="form-control" style="height:auto;">
<div class="radio">
<label class="noBold-text" style="font-size: 1em">
<input id="factorSelect_email" name="factorSelect" type="radio" value="EMAIL" />Send me an email
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>
</label>
</div>
<div class="radio">
<label class="noBold-text" style="font-size: 1em">
<input id="factorSelect_sms" name="factorSelect" type="radio" value="SMS" />Send an SMS to my phone
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>
</label>
</div>
</div>
</div>
</div>
$("#forgotPasswordForm").validate({
rules: {
fpUsername: {
required: true,
minlength: 3
},
factorSelect: {
required: true
}
},
messages: {
fpUsername: {
required: "Please enter your username or email",
minlength: "Your username must be at least {0} characters"
},
factorSelect: {
required: "You must select a recovery method"
},
},
highlight: function (element, errorClass, validClass) {
$(element).parents(".form-group").addClass("has-error").removeClass("has-success");
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".form-group").addClass("has-success").removeClass("has-error");
},
});
The has-error class never gets applied to the radio button group.
I reproduced the error you have in this CodePen...
The error message produced by jQuery Validate is positionned right after the invalid element... Which is the default.
Now you can position that error message elsewhere, using errorPlacement.
In this Solution, I just placed it right after the parent .input-group. I'm sure that is the puzzle piece you where looking for.
;)
errorPlacement: function(errorLabel, invalidElement){
if( $(invalidElement).is("[type='radio']") ){
var inputGroup = $(invalidElement).closest(".input-group");
inputGroup.after(errorLabel);
}
},
EDIT
With your full code, that is easier to work...
;)
The default behavior of a button in a form is to submit (Reference, see "type").
So if the type is omitted, that is what it does.
And the .validate() function isn't triggered by a button type="button".
So...
You have to prevent the default submit in order to validate first.
Then, submit if the form is valid.
This is achieved by .preventDault() and submitHandler
$("#forgotPasswordForm").on("submit",function(e){
e.preventDefault(); // Prevents the default form submit (Have to validate first!)
})
.validate({
// Skipping some lines here...
submitHandler: function(form) {
form.submit(); // Submits only if the form is valid
}
});
Updated CodePen
Ok, fixed it. Thank you for the help above with the placement of the error message. That was not my initial issue but did come up once I got the error to display at all. Your fix works great.
My primary issue turned out to be a CSS conflict with some styles that turn the radio buttons into pretty font-awesome icons. The little snippet that hides the default radio buttons causes the validation to fail as it must only look for visible fields. I set the height to zero instead and so far it seems to work.
.checkbox label input[type="checkbox"],
.radio label input[type="radio"] {
/*display: none;*/
height:0;
}

bootstrapValidator-enable and disable field validation

So; I tried to check couple of solutions online but I couldn't find a solution that solve my problem regarding enabling and disabling field validation using bootstrapvalidator.
I have a field that supposed to give error when someone enter a negative number (e.g -4,-100,-545 etc.), and any number that is not numeric (e.g 4.4.4, 4.r, 4t etc).
But I want to put a condition that wont give error when a user type in -999.
Code is working well when a user enter other number that is not a negative and nob-numeric. And if a user enters negative or non-numeric number, error is displayed. The problem when user enters -999 it validate true(don't show error), but if user change number(-999) to other number such as negative number and nun-numeric number, my field validation stop working (meaning don't show any error though it was supposed to show).
So how can I enable and disable field validation or setting up a condition on field validation to solve my problem using bootstrapValidator..???
Hope you guys have already come across with such a problem and I hope you can help me solve the puzzle.
You can try it here: https://jsfiddle.net/os3b0dqx/ to see how it works
my template.html looks like:
<form class="well form-horizontal" action=" " method="post" id="myform">
<div class="form-group">
<label class="col-xs-3 control-label">Length</label>
<div class="col-xs-5">
<input type="text" class="form-control" id="length" name="length" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-1">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
<script>
$(document).ready(function () {
$('#myform').bootstrapValidator({
feedbackIcons: {
validating: 'glyphicon glyphicon-refresh'
},
fields: {
length: {
validators: {
greaterThan: {
value:0,
message: 'The value must be greater than or equal to zero'
},
numeric: {
message: 'The value is not a number',
thousandsSeparator: '',
decimalSeparator: '.'
},
notEmpty: {
message: 'Please fill the length' }
}
},
}
}).on('click keyup input change','[name="length"]',function(){
if ($(this).val() == -999) {
$('#myform').bootstrapValidator('enableFieldValidators','length',false);
}
else{
$('#myform').bootstrapValidator('validateField','length');
//$('#myform').bootstrapValidator('enableFieldValidators','length',true);
// both "validateField" and "enableFieldValidators" doesn't work for me..
}
});
});
change this if ($(this).val() == -999) to if ($(this).val() == '-999')

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!

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