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.
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;
}
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;
};
So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
So I did the following but can't get it to work:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.
Thanks.
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try
var phone = /^\d*$/;
That will match the empty string too; use + instead of * if you want at least one digit.
You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate(), but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process:
$('#myform').submit(function(){
return validate();
});
validate() would return false, and then your handler returns the same.