I am trying to make phone number required if some logic holds true. When logic does hold true i see first two phone number fields say phone number is required even though i have entered something in them, only the third one doesn't show error. The error only goes away when i manually click on first two fields.
I also tried calling valid() method on first two phone fields inside phoneValidation method but it was causing infinite loop understandably. I suppose i can make this work by adding different validator methods for all three phone boxes but is there an elegant way to do this?
<div class="form-inline" style="margin-top: 5px;">
<input type="text" name="phone1" id="phone1" class="form-control" maxlength="3" size="3" /> -
<input type="text" name="phone2" id="phone2" class="form-control" maxlength="3" size="3" /> -
<input type="text" name="phone3" id="phone3" class="form-control" maxlength="4" size="4" />
</div>
JS
$("#thisForm").validate({
rules: {
"phone1" : { maxlength: 3, minlength: 3, digits: true, phoneValidation: true},
"phone2" : { maxlength: 3, minlength: 3, digits: true, phoneValidation: true},
"phone3" : { maxlength: 4, minlength: 4, digits: true, phoneValidation: true}
}
});
$.validator.addMethod("phoneValidation", function(value, element) {
// some logic
if ($("#someField").is(":checked"))
return true;
if (!$("#phone1").val() || !$("#phone2").val() || !$("#phone3").val()) {
return false;
}
return true;
}, "phone is required.");
I kept the original solution. The validation errors on the first two fields goes away when you click on them or submit form. Not ideal but not a show stopper!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have two fields mobile number and alternate mobile number.need java script validation.1st number should not be same as 2nd mobile number.I have tried something and it is working. I edited my question, with correct answer
This is html code:
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" id="mbno" placeholder="Mobile" name="mbno" maxlength="13" required /></div>
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" id="altmbno" placeholder="Alternate Mobile" name="altmbno" maxlength="13" />
<script type="text/javascript">
$.validator.addMethod("mobile_not_same", function(value, element) { // Method to check if 2 mobile numbers are same or not
return $('#mbno').val() != $('#altmbno').val() // mbno and altmbno are input id's
});
$(function(){
$("#save").prop('disabled', true);
// validate signup form on keyup and submit
$("#defaultForm").validate({ // defaultForm is a form id
rules: {
altmbno: {
required: true,
number : true,
mobile_not_same: true,
minlength: 10
},
mbno: {
required: true,
number : true,
mobile_not_same: true,
minlength: 10
},
},
messages: {
mbno: {
required: "Please enter 10 digitsmobile number !",
mobile_not_same: "mobile numbers should not be same",
},
altmbno: {
required: "Please enter 10 digitsmobile number !",
mobile_not_same: "mobile numbers should not be same",
},
}
})
});
</script>
Question shows less effort. Hope you remember next time.
You can easily achieve this using Jquery. Add Id to each input. Code will look like this.
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" placeholder="Mobile" name="mbno" id="num1" maxlength="13" required /></div>
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" placeholder="Alternate Mobile" name="altmbno" id="num2" maxlength="13" /></div>
Add script and Use keyup from jquery while typing second mobile number.
$("#num2").keyup(function(){
var bla = $('#num1').val();
var bla1 = $('#num2').val();
if(bla === bla1){
console.log('equal');
}else{
console.log('not equal');
}
}
If you don't want while typing and just after form submit, then write function and get values of two fields using Jquery (you can also get it by using getElementById). After that compare that two values.
Comparing two numbers should not be that hard
function validate() {
var mbno = document.getElementById('mbno');
var altmbno = document.getElementById('altmbno');
if (mbno.value === altmbno.value) {
alert("Error! The mobile numbers should not be the same");
} else {
alert("Numbers Are OK");
}
}
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" id="mbno" placeholder="Mobile" name="mbno" maxlength="13" required /></div>
<div style="color:red" class="col-sm-3"><input type="text" class="form-control" id="altmbno" placeholder="Alternate Mobile" name="altmbno" maxlength="13" /></div>
<button onclick="validate();">Submit</button>
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 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 have a dojo form which uses the dojo form wizard. The form has one tag. Within the form tag is a dojo.wizard.Wizard. It is a requirement that the wizard be inside a form tag. Within the Wizard is several wizard panes.
On each wizard pane i have form fields. I am preforming validation by calling a method on the wizard pane passFunction. However for the dojo validation to work i must get the children elements on the form and call the validate method against the form. This validates the entire form.
This is not practical for what i want to do since the first pane has n form elements, the second pane has n elements. When the validate function is called from the passFunction on the first pane it validates elements on other panes which are inaccessible yet.
How can i specify items to be validated for the form? I would like to validate only items on the first pane then move to the second pane and validate only those items. Under is my code structure:
Jsp
<form data-dojo-type="dijit/form/Form" id="myForm" />
<div data-dojo-type="dojox.widget.Wizard" data-dojo-props="style: 'height:450px; width: 600px'">
<div dojoType="dojox.widget.WizardPane" id="page1" passFunction="validatePage1" >
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'First Name Required !'" id="fnameTextBox" title="First Name" placeholder="Your First Name" />
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Last Name Required !'" id="lnameTextBox" title="Last Name" placeholder="Your Last Name" />
</div>
<div dojoType="dojox.widget.WizardPane" id="page2" passFunction="validatePage2" >
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Age Is Required !'" id="ageTextBox" title="Age" placeholder="Your Age" />
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="
regExp: '[\\w]+',
required: true,
invalidMessage: 'Phone Number Required '" id="phoneTextBox" title="Phone" placeholder="Your Phone Number" />
</div>
</div>
</form>
In validatePage1 i would only like to validate surname and firstname fields and once that is completed when i move to the second page i would like to validate age and phone number. I am only checking for nulls presently.
Javascript
dojo.require("dijit/form/Form");
dojo.require("dijit/form/Button");
dojo.require("dijit/form/ValidationTextBox");
dojo.require("dijit/Tooltip");
function validatePage1(){
var myform = dijit.byId('myForm');
myform.connectChildren();
myform.validate();
}
We need to know what are the fields to be checked. So we can add a class to those fields for this purpose. Lets call it "chkThisField".
//a function to validate the given field
var highlight = function(widget){
if(!widget.validate) return true;
widget._hasBeenBlurred = true;
widget.validate();
};
var fields = dojo.query(".chkThisField");
//above line is to get array of all fields with the "chkThisField" class
fields.forEach(function(fld){
var widget = dijit.getEnclosingWidget(fld);
highlight(widget);
});
So now,with the help of class selector, we have successfully validated specific fields only.
This is my form :
<FORM id="form1">
Fields :
<fieldset name="titles">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
</fieldset>
</FORM>
How can I check if at least two out of these four fields are filled? Here's what i'I've tried :
$('#form1').validate({ // initialize the plugin
rules: {
title: {
required: "input[name='title']",
minlength: 2
},
messages: {
title: "You must fill at least two titles!"
}
}
});
But it's not working, it always returns a valid form... I'm a newbie to jQuery, any help would be appreciated.
For 1 statement to grab both 'select' and 'input' elements, simply change your single jQuery selector to a multiple selector,
Eg:-
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
Try this with the button:
$("#submit_button").click(function(){
if($('input[text]').length < 2) {
alert('at least two text inputs are filled');
return false;
}
});