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;
}
Related
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 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?
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')
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!
I am trying to use jQuery Validate to prevent my ajax form submit when three fields contain any characters other than digits. Apparently I'm doing something wrong, but I can't see what.
EDIT: There seem to be two errors. My validation rules use the field ID instead of the field name. However, after fixing that problem, the form still validates unexpectedly..
This is my jQuery code:
(function() {
$(document).ready(function() {
formSubmits();
/**
* Handles all the form submits that go on.
* This is primarily the ID search and the form submit.
*/
function formSubmits() {
/*** SAVE RECIPE ***/
// validate form
$("#category-editor").validate({
rules: {
"time-prep": {number: true}, /* not sure why validation doesn't work.. */
"time-total": {number: true}, /* according to this, it should: http://goo.gl/9z2odC */
"quantity-servings": {number: true}
},
submitHandler: function(form) {
// submit changes
$.getJSON("setRecipe.php", $(form).serialize() )
.done(function(data) {
// de-empahaize submit button
$('.footer input[type=submit]')
.removeClass('btn-primary')
.addClass('btn-default');
});
// prevent http submit
return false;
}
});
}
});
})(jQuery);
Here's what I see in the inspector when I put a breakpoint inside the submitHandler. It is getting to the submitHandler despite bad input (a value of 'dsdfd' instead of '123')
This is the relevant markup:
<form id="category-editor" class="form-inline" method="get">
....
<div class='form-group'>
<div>
<label for="time-prep">Prep time (min):</label>
<input value="" id="time-prep" name="activeTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-prep-desc" type="number">
<input value="" id="time-prep-desc" name="activeTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="time-total">Total time (min):</label>
<input value="" id="time-total" name="totalTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-total-desc" type="number">
<input value="" id="time-total-desc" name="totalTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="quantity-servings">Servings:</label>
<input value="" id="quantity-servings" name="servings" class="form-control jqValidateNum" type="number">
</div>
</div>
....
</form>
You've got your rules set up with the "id" values for the <input> elements instead of their "name" values. Should be:
rules: {
"activeTime": {number: true},
"totalTime": {number: true},
"servings": {number: true}
},
edit — now that you've fixed that, I think the problem is that the "value" properties of the input elements are empty, because you've declared them type=number. Firefox and Chrome let you type anything into the fields, but they won't have a non-empty value unless the fields really do contain numbers.
If you also mark the fields as required, then it works. fiddle