Can you please tell me how to do validation in a form which is generated dynamically? I am using one plugin dform.js which converts JSON to form. I am to do that validate of fields.
http://jsfiddle.net/Xe3FG/2/
I take help from this.
https://github.com/daffl/jquery.dform
In my demo, I take 2 number fields. If the user enters a string and go to next field, I need it to display an error in front of the field, "please enter only numbers." I need the same with second field.
Can we do only using drom.js or validation.js?
I am able to validate when user enters data in the field and then press enter.
So I used blur event. It is not a good practice to use blur event on every field. Can you give a different way and a good way to validate?
("#totalRetryCount").blur(function() {
// Number element type returns empty value when NaN
if ( $('#totalRetryCount').val() == '' )
alert('enter a number');
});
$("#totalRepeatCount").blur(function(event) {
// Number element type returns empty value when NaN
if ( $('#totalRepeatCount').val() == '' )
alert('enter a number');
I used these two blur events. I don't want to use these events. Can we do these validations another way?
I've already explained to you how to do this in your last question and provided you with a fully working example which you've seemed to completely ignore. In this case, you would just need to check if the value is an empty string, as that is the default value of a number type input field containing non-numeric data.
Fiddle demo
$("#testSuiteConfigurationform").validate(validateInputParameters());
function validateInputParameters() {
jQuery.validator.addMethod("onlyNumbers", function(value, element) {
return value != "";
}, " Please enter only numbers");
var validation = {
onfocusout : function(element) {
$(element).valid();
},
rules : {
totalRetryCount: { onlyNumbers: true }
},
};
return validation;
};
Related
Here Is My Logic:
It Didn't Work :(
function ShowDropMenu(){
var numfiled = document.getElementById('numpeple'); //I Want Whenever Someone Enters a Number In Input Field It Should Display The Dropdown Menu?
if (numfiled < 0 ) {
document.getElementById('dropmock').style.display="block"
}
else{
alert('Please Add Atleast 1 Or More People to go ahead)
}
}
I Don't Know What's Went Wrong?
numfiled is an Element, so comparing it with a number won't do anything meaningful.
You want the value of the Element. Additionally, since the value is always a string, you want to parse it as a number. For example:
var numfiled = parseInt(document.getElementById('numpeple').value);
Note: This assumes #numpeple refers to an <input> element, inferred from the comment in the code: "Someone Enters a Number In Input Field"
I have a form wherein a user can enter a value associated with a nullable long property of my ViewModel. But because I have an 'onblur' event on that text box, I am trying to validate the entered value in my textbox.onblur() event and ensure that it does not exceed the C#'s, long.MaxValue. Here is my "blur" code on that text box.
var value = $(this).val();
console.log(value > 9223372036854775807);
if (value<= 1 || value > 9223372036854775807) {
$('#divValueError').text("Invalid Value!");
return false;
}
But Javascript is returning false on that console.log statement if I enter 9223372036854775808. How do I check if the number entered by the user falls within the limits of a C# long value?
I understand 64 bit numbers are not supported by Javascript. I also could not get my [Range] data annotation on that property to fire before this blur event is called, even though I tried
if (!$(this).valid()) {
return false;
}
Please let me know how I can throw a client side error if the value entered by the user falls outside the boundaries of a C#'s long data type value.
Thanks!
Perfect Answer :
I am Providing example that will solve your problem.
In this , you first have to convert your value in string and then in biginteger.
Reference link added for better guidance.
var valuecompare = BigInt("9223372036854775808");
var valuebase = BigInt("9223372036854775807");
console.log(valuecompare);
console.log(valuebase);
if (valuecompare > valuebase) {
console.log('greater value');
}
else{
console.log('less value');
}
Reference Link : https://www.smashingmagazine.com/2019/07/essential-guide-javascript-newest-data-type-bigint/
I have an advanced search form in a custom CMS. I need to check to make sure that the user doesn't try to submit the form without at least one field populated. No problem; this is a very stripped-down version:
var noText = false;
if(!$('#advancedId').val() && !$('#advancedTitle').val() &&
$('#advancedCoupon').val() && !$('#advancedDesc').val() ) {
noText = true;
}
if(noText) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
noText = false;
return false;
}
But we have that one QA guy who just has to really do his job, and deliberately tries searches that there's no way our client would ever do. He submitted a bug indicating that if he entered a space in every field, it passes and tries to submit.
So I tried trimming the values like this:
if(!$('#advancedId').val().trim() && !$('#advancedTitle').val().trim() &&
$('#advancedCoupon').val().trim() && !$('#advancedDesc').val().trim() ) {
noText = true;
}
This of course works if I actually enter a space in all of the fields, but throws a "Cannot read property 'trim' of null" error if I try to submit it with a space in one field, and nothing in the others.
Yes, I could do something like this:
if($('#advancedId').val()) {
$('#advancedId').val($('#advancedId').val().trim());
}
Yes, I could make it somewhat shorter with a terniary, but I'd still have to do that for over a dozen fields. Is there a better way to do this?
I would probably select them all and then do a filter. Though to make it less tightly coupled, I'd probably put a class on them and select with that instead of all the ids.
//select all the fields concerned and filter on them for non-blank values
var nonBlankFields = $('#advancedId, #advancedTitle, #advancedCoupon, #advancedDesc').filter(function(){
//default to an empty string if for some reason the value doesn't exist
return ( this.value || '' ).trim().length > 0
});
if (!nonBlankFields.length) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
return false;
}
I'm working on a simple form that I need to validate against UK postcodes. No problem there but I need to validate depending on the character length. The user can input only the first half of a postcode (i.e. SW1) or a full postcode (i.e. SW1 1AB).
I thought the best approach would be to check the length on KeyPress and validate against RegEx for either half a postcode or the whole thing. See below:
jQuery('.ValPostCode').keyup(
function(){
if (jQuery(this).length < 5){
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw]))/.test(value);
}, "Please enter a valid postcode");
} else if (jQuery('.ValPostCode').length > 4) {
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /^(GIR\\s{0,1}0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\\s{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$/.test(value);
}, "Please enter a valid postcode");
}
});
So, if the char length of .ValPostCode is less than 5 it validates only for the first half of a UK postcode, else it checks for a full and valid UK postcode.
At one point I was outputting the length of .ValPostCode but it always stopped at 1 (first keypress) and then didn't carry on any further (i.e. wouldn't count up with subsequent keypresses).
I hope I've explained myself clearly enough, please let me know if I'm not being clear.
I've searched for similar problems to try and fix this for myself but I couldn't find anything. Any help appreciated!
The length of $(selector).length (or jQuery(selector).length) will always be the number of elements on the screen that match the given selector. Try using $(selector).val().length to get the value of a form element and check its lenght instead.
It seems as though you are setting up validator rules on every keypress unnecessarily
When the page first loads, you should only need to call something like this:
jQuery.validator.addMethod("ValPostCode", function(value, element) {
if(value.length < 5) {
return (insert partial postcode check here);
} else {
return (insert whole postcode check here);
}
}, "Please enter a valid postcode");
And should only call it once. JQuery will pick up the error on submit/change depending on how it is configured.
So there is no need for a keyUp event.
The main problem you were having (as someone else has already pointed out) is that you were returning the length of the jQuery object rather than the length of its value attribute.
EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0