Check validation for numbers only - javascript

following is my piece of code which checks if the input format is EMAIL which comes from the form input or not and validates accordingly i want to know how can i modify the following code that validates if the input was only number
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}

Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
$.isNumeric("-10"); // true

if (email.match(/[0-9]+/)) {
//it's all numbers
}
EDIT
As mentioned in the comments, to ensure that the entry is ALL numbers, the regex would have to include the begin and end characters, ^ and $:
if (email.match(/^[0-9]+$/)) {
//it's all numbers
}
Or even more succinctly:
if (email.match(/^\d+$/)) {
//it's all numbers
}
I don't deserve the credit for that fix, but I did want to correct it for anyone who may come find this later.

I would use:
if(isNaN(email*1)){
//evaluated to NaN
}else{
//evaluated to number
}
In this case the (email*1) have the possibility to evaluate to NaN, and thus will fail the check because the list of falsish values are 0,"",false,null,undefined,NaN

Check if converting the email address to a Number object returns a 'Not a Number' value; if not, the input was a number. The code would look like this:
if(!isNaN(Number(email)) {

Related

Having confusion regarding how to pass value in a var through prompt

<script>
var p=prompt("how old are you","");
if(p)
alert(p+" is your age");
else
alert("You dint entered any input or you have entered a non-integervalue");
</script>
This is my javascript code. Suppose i enter my age 0.
Then p=0 this implies the else part of the code will execute. But the code is executing the if part!
Why is it happening?
I'm new to Web-development , Please Help.
Thank You!
parseInt() the result of the prompt, that means, parsing the string result to an integer
Now, if the input is "0", it is parsed to 0, and 0 == false.
Thus the "else" condition would take place, as required.
Also, if a non-integer string is entered, such as alphabets, the result would be a NaN and the else part would occur
var p=parseInt(prompt("how old are you",""));
if(p) {
alert(p+" is your age");
}
else {
alert("You dint entered any input or you have entered a non-integervalue");
}
Just write this code :
var p=prompt("how old are you","");
alert(typeof(p));
You will see that it is a string. "0" is a string, so it will be evaluated to true as it is not empty or null.
So, parse it to a number before doing anything.
If you want to ensure the prompt input is number, you should use isNaN function to check the input.
var p=prompt("how old are you","");
if(!isNaN(p)) alert(p+" is your age");
else alert("You dint entered any input or you have entered a non-integervalue");

identifying numbers using javascript

How can I make a function that takes a string and checks if it is a number string or if it includes letters/other characters? I have no idea what to do... RegExp takes too long so is there another way?
You have to use isNaN() function (is Not a Number). It will return you true if it's not a number (that mean that it contains letter) and false if it's one.
Source :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You can check for isNaN and see if value is number if you don't want to go with RegExp.
let inpArgs = Number.parseInt(input);
if(!Number.isNaN(inpArgs)){
// this check ensures that your input is number
// Do what you have to do
}
else{
// Handle the error
}
But I would prefer the one line check using RegExp any day like below.
if(/^\d+$/.test(Number(input))){
// this says your input is Number
}
You can use typeof oprator to check whether it is a number or string.
function(anything){
if(typeof(anything)==='number'){ //do something} }
if(typeof(anything)==='string'){ //do something} }
Hope I answer your question.
Thanks.
You can use typeof in JavaScript to identify input Like
alert(typeof <your input>); or var identity = typeof <your input>;
and whatever string alert that match in Condition Like
if (identity == <alert message>){do something}else{do something}

Struggling with some javascript, password / username error display

Note, I will validate everything with PHP on form submission, but I'd like to display it instantly to the user if possible.
For the username I am trying to detect if it only contains whitespace, if it's less than 8 chars/numbers and if it only contains normal valid letters and no symbols.
This does not seem to work:
$("#username").change(function() {
$("#username").removeClass("error");
var letterNumber = /^[0-9a-zA-Z]+$/;
var username = $("#username").val(); // get value of password
if (!(username.value.match(letterNumber)) {
// return error
}
if (username.length < 8) {
// return error
}
if (username.trim().length() > 0) {
// return error
}
});
And for the password, I want to allow all symbols, all numbers, all letters, minimum 8, and trim for whitespace. It does not seem to work though.
Change from this:
if (!(username.value.match(letterNumber)) {
// return error
}
to this:
if (!(username.match(letterNumber)) {
// return error
}
You've already retrieved the .value when you used .val() earlier so username is already the desired string.
Also, the .trim() test is not correct as .length is a property all by itself, not a method). But, you can just remove this because your regex test before has already eliminated empty strings and strings with only whitespace so this test (even when corrected to be proper javascript) is unnecessary.
if (username.trim().length() > 0) {
// return error
}
In the future, you should be looking in your browser error console or debug console because it would have told you something like undefined doesn't have a method .match() and given you that exact line number as the source of the error.

JavaScript/jQuery - Validating based on length

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.

Javascript regex 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.

Categories