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!
Related
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>?
I have a submit button for an unsubscribe page, I would like to remove a "disabled" class to the button when user inputs a valid email. As of now I have the class being toggled based on "input" which kind of works but I would rather the user have to input a valid email to remove the "disabled" class. I am using jquery validation for the validation I'm just not sure how to base the buttons class toggle with jquery validate input. Any Ideas?
HTML:
<div class="form-group">
<input type="email" class="form-control email-input input-lg"
name="email">
</div>
<button id="unsubscribe-submit"
class="disabled">
<span class="btn-text>Submit</span>
</button>
jQuery:
$($emailInput).on('input', function() {
$('#unsubscribe-submit').toggleClass('disabled', this.value.trim().length === 0);
});
jQuery Validation:
($unsubscribeForm.length) {
$unsubscribeForm.validate({
errorClass: 'has-error',
errorElement: 'span',
debug: true,
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: {
required: 'An email address is required.',
email: 'Please provide a valid email address.'
}
}
});
}
As you are already using the HTML input type "email", you can make use of modern browsers' integrated form validation. Calling checkValidity() on an input element will tell you whether its current value is regarded as valid or invalid by the browser. Use this to either remove or add the class to the button. In this demonstration, I also showed how to add/remove the disabled attribute. It would be preferrable to simply using a class, because you can still click the button even if it has the disabled class.
$(document.querySelector('input[type="email"]')).on('input', function() {
// use this to add/remove a class
$('#unsubscribe-submit')[this.value.length && this.checkValidity() ? 'removeClass' : 'addClass']('disabled');
// or this to add/remove the disabled attribute
$('#unsubscribe-submit').attr('disabled', this.value.length && !this.checkValidity());
});
.disabled,
button[disabled] {
opacity: 0.5;
cursor: not-allowed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<input type="email" class="form-control email-input input-lg" name="email">
</div>
<button id="unsubscribe-submit" class="disabled" disabled>
<span class="btn-text">Submit</span>
</button>
You do not even need JavaScript to change the button with HTML5 validation. Use input email and set it to be required. When it is not valid, the form is invalid which you can target the button to set your style
form:invalid button {
color: red;
}
<form>
<input type="email" required>
<button> submit</button>
</form>
I'm using Jquery Validate in my web form. I have an empty input, however the input is populated dynamically with text on the click of a button. Validation doesn't seem to work when I do this.
when the input is empty, on submit validation works (input turns red).
when input is populated dynamically, it stays red, it should turn green
My code is below and here's a fiddle;
In the fiddle, click submit when the input is empty, then toggle the button to No - the input should change to green without having to submit the form again.
HTML
<p>Does this item have an inventory number?</p>
<p>
<form id="myForm" method="post">
<input type="checkbox" class="input-large" value='1' name="btn" id="btn">
<div class="control-group">
<div class="controls">
<div class="input-prepend">
<input type="text" class="input-large" id="type" name="type" placeholder="Inventory Number">
</div>
</div>
</div>
<input type="submit" class="submit" value="Submit">
</form>
Jquery
$(function() {
$('#btn').bootstrapToggle({
on: 'No',
off: 'Yes',
onstyle: 'danger'
});
})
$("#myForm").validate({
rules: {
type: {
required: true,
minlength: 2
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
unhighlight: function(label) {
$(label).closest('.control-group').addClass('success');
},
});
$("#btn").on("change", function() {
if ($(this).prop('checked') == true) {
$("#type").attr("readonly", "true");
$("#type").val("Personal Item");
$("#type").rules("remove", "number minlength maxlength");
}
if ($(this).prop('checked') == false) {
$("#type").removeAttr("readonly");
$("#type").val("");
$("#type").rules("add", {
required: true,
minlength: 5,
maxlength: 6
});
}
});
You use some custom highlight and unhighlight on the control-group.
Just add this to the checked==true condition:
$("#type").closest('.control-group').removeClass("error").addClass("valid");
$("#type").next(".error").remove();
Since the rule is removed, it is not re-validated...
Your Fiddle updated.
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>
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;
}