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')
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>
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;
}
I am using http://bootstrapvalidator.com/ with visual studio in bootstrap asp.net project.
Problem I am having that I can never get validate button to actually validate like it does in examples, it validates fine when I start typing into textbox, but never validates when I click on button following examples.
Another issue is I don't know how to call my c# method which will get value from textbox after validation was successful, I can call my method on button click, but I want it to happen just after validation was successful .
What I am looking for is simple example how to make submit button validate fields and then call my c# method which will read values from inputs.
I been unable find even single example online , and I dont know much about javascript.
Here is some testing code I have
<div class="form-group" id="nameEmail2">
<div class="form-group">
<label for="inputContactName" class="col-sm-5 control-label">Contact Name </label>
<div class="col-sm-7">
<input type="text" class="form-control" name="fullName1" id="TextBox1" placeholder="Contact Name" maxlength="50"/>
</div>
</div>
<div class="form-group">
<label for="inputContactEmail" class="col-sm-5 control-label">Contact Email <b>*</b></label>
<div class="col-sm-7">
<input type="text" class="form-control" name="email1" id="TextBox2" placeholder="Contact Email" maxlength="50"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<button type="submit" runat="server" onserverclick="submitValidate" class="btn btn-default">Validate</button>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#nameEmail2').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fullName1: {
validators: {
notEmpty: {
// enabled is true, by default
message: 'The full name is required and cannot be empty'
},
stringLength: {
enabled: true,
min: 8,
max: 40,
message: 'The full name must be more than 8 and less than 40 characters long'
},
regexp: {
enabled: false,
regexp: /^[a-zA-Z\s]+$/,
message: 'The full name can only consist of alphabetical, number, and space'
}
}
},
email1: {
validators: {
emailAddress: {
message: 'The value is not a valid email address'
}
}
}
}
});
});
</script>
I have removed most of asp objects and almost nothing runs at server any more, but that didnt help much here is my codebehind method
protected void submitValidate(object sender, EventArgs e)
{
string contactName = Request.Form["fullName1"];
string email = Request.Form["email1"];
System.Diagnostics.Debug.Write("test",email);
}
Found an answer to my own question
http://thuyvk.com/article/validate-form-su-dung-bootstrapvalidator-cho-website-aspnet-224
Be careful with google translate, will translate code into some random html code
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
I am using jquery validation plugin to validate my form. I have one field that I don't want to validate but in some way it is validated anyway and I get the error message "Please enter no more than 5 characters."
The field that is validated is a type=file field and I use it together with the Fynework jQuery MultiForm plugin. It's not validated when I try to submit the form, only when I chose file that has a name longer than 5 characters (I think, short names work long doesn't).
I have tried adding the class .ignore to the field that is validated and added that the ignore rule to my validat(), not difference in behaviour.
What can the problem be?
Here is my validat() method, I also include the point at which I add that method:
function addNewTicketValidation(){
$("#newticketform").validate({
ignore: ".ignore",
errorContainer: "#messageBox1",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li",
debug:true,
rules: {
title: "required",
description: "required"
},
messages: {
title: "Titel saknas",
description: "Beskrivning saknas"
}
});
}
$("#newticketmanu").live('click',function(event){
$("#adminarea").load("http://" + hostname + "/" + compdir + "/modules/core/newticket/newticket.php", function(){
$('#my_file_element').MultiFile();
addNewTicketValidation();
});
});
My form:
<form method="post" enctype="multipart/form-data" id="newticketform" class="MultiFile-intercepted" novalidate="novalidate">
<input type="hidden" value="2000000" name="MAX_FILE_SIZE">
<label for="title">Rubrik</label> <input type="text" name="title" id="title"><br><br>
<label for="description">Beskrivning</label> <textarea name="description" id="description" cols="50" rows="15"></textarea><br>
<div id="my_file_element_wrap" class="MultiFile-wrap"><input type="file" maxlength="5" name="file[]" id="my_file_element" class="multi ignore MultiFile-applied" value=""><div id="my_file_element_wrap_list" class="MultiFile-list"></div></div>
<div id="files_list"></div>
<input type="submit" value="Upload" name="upload">
</form>
What can the problem be and how to fix it?
Thanks!
Remove the maxlength="5" attribute from the file input. This is read by the validation plugin and added as a rule (line 812 here https://github.com/jzaefferer/jquery-validation/blob/1.9.0/jquery.validate.js). Checking the specifications (http://www.blooberry.com/indexdot/html/tagpages/i/inputfile.htm), max length still means character length even on a file input, so if you want to limit the user to 5 file uploads you'll need some other method of achieving this.