javascript form validation textfield length - javascript

i got a problem on validate the student ID, it require 10 numbers, the problem i met is when i key in a valid student ID, it still return false. Please help me to check mycoding, thank you very much.
example of my Student ID = "1101106363"
if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
update: [link]http://jsfiddle.net/rVswq/1/

You need to use document.getElementById method to select the element properly.
var el = document.getElementById("yourid");
if (!(isNaN(el.value)) || (el.value.length &lt 11))
{
alert("Please enter the correct Student ID");
el.focus();
return false;
}

There is something strange here.
You are checking if the value is null, OR if it IS a number (isNaN returns true if the value IS NOT a number, if you place !isNaN the result is true if the value IS a number), OR if the length is inferior to 11.
If you want to be sure that the inserted value is not null, a number and its length inferior to 11 you should write
if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10))

It looks to me like you don't need the NOT operator
if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}

Your IF statement is wrong. You want:
if ( (document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11) )
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}

Your if statement will catch students ids with length less to or equal to 10.
Test against length like 10 instead

Related

Prompt user for entry, thank them for entry Javascript

The first prompt shows up, and nothing else happens, even if I enter a number or try to push through the prompt without entering anything.
So far I've written this code:
var ratingEntry = prompt("We would like for you to review . Please enter a
rating between 0.0 - 5.0?");
if (ratingEntry === undefined) {
prompt('Please enter a rating from 0-5!');
} else if (ratingEntry === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (ratingEntry === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
I've tweaked it several times to no avail.
The problem you have is that prompt return a string and you do check for equality without type coersion.
1 === 1 is true
"1" === 1 is false
Basically "1" is a string, and 1is a integer.
Change ===to == and you would ignore "type" check. Or just check for "1" instead of 1
To compare Integer you need to first parse ratingEntry into Integer then compare and for first condition It is coming blank not undefined so put both check with OR in first condition.
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
if (typeof ratingEntry === undefined || ratingEntry.trim() == '') {
prompt('Please enter a rating from 0-5!');
} else if (parseInt(ratingEntry) === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (parseInt(ratingEntry) === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
and last thing I am not sure what you are doing with this code but It should be like this
Use
teacherRatings.push(ratingEntry);
Instead of
teacherRatings.push('ratingEntry'); //this push ratingEntry as string in teacherRatings not as a value of variable
You may want to parse the input to Float and then use a while loop until the input is valid:
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
var ratingNum = parseFloat(ratingEntry)
while (isNaN(ratingNum) || ratingNum < 0 || ratingNum > 5) {
ratingNum = parseFloat(prompt('Please enter a rating from 0-5!'));
}
teacherRatings.push(ratingNum);
prompt('Thank you!');
A prompt will return a string. And you need to always capture it to compare, so I would do:
var message = "We would like for you to review . Please enter a rating between 0.0 - 5.0?";
while(ratingEntry = prompt(message)) {
if (ratingEntry === '' || ratingEntry < 0 || ratingEntry > 5) {
message = 'Please enter a rating from 0-5!');
} else {
break;
}
}
etc. because you are using === which compares value as well as type (e.g. 1 === 1 and 1 !== '1', but 1 == '1')

Javascript form validation. Street Number. How to set accepted numbers to 1 but accept numbers 1-99999

I'm having trouble with some JS form validation.
I've linked a external .JS script in my html head section with function rules.
I have the following function rule in the .JS script file:
function IsValid5DigitStreetNumber( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if (IsBlank(str) || (str.length != 1) || !IsInt(str, false))
isValid = false;
return isValid;
}
I have the following JS code in my html head section
if(IsValid5DigitStreetNumber(document.orderbooks.querySelectorAll("[name=streetnumber]")[0].value)) {
} else {
alert("Street Name invalid! Please enter a valid 1-99999 digit street number!:");
return false;
}
It's throwing up the alert message every time even when I enter a correct number.
I want to be able to accept a number between 1 and 99999 in the html form for street number. What do I change to get it working?
Edited:
After determining requirements at last:
function IsValid5DigitStreetNumber( str ) {
if (!/^\d{1,5}$/.test(str)) {
return false;
}
const num = parseInt(str, 10);
return num >= 1 && num < 1e5;
}

How to add input text validation for true and false?

Friends, i can't figure it out how to add text validation for admin var.
Point is user enters either 0 or 1 or true or false in the form. It's ok with checking numbers but i can't make up valid check for text input, e.g. true-e-e-e, fasleee, abra-cadabra, etc.
<script type="text/javascript">
function submitEmployeeForm() {
// getting the employee form values
var name = $('#name').val().trim();
var age = $('#age').val();
var admin = $('#admin').val();
if(name.length ==0) {
alert('Please enter name');
$('#name').focus();
return false;
}
if(age <= 0) {
alert('Please enter valid age');
$('#age').focus();
return false;
}
if(admin < 0 || admin > 1) {
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}
return true;
};
</script>
I tried the following 2 options:
!admin.isEqual("false") || !admin.isEqual("true")
admin.valueOf()!="true" || admin.valueOf()!="false"
as a result is it does not pass any text including true and false.
If you want to accept only '0','1','true','false' as valid then use something like this
if (['0','1','false','true'].indexOf(admin.toLowerCase()) === -1) {
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}
What we do is create an array which holds the valid texts, and then use indexOf(parameter) which searches the array for any element matching the passed parameter. If it is found it returns the position it was found in the array, if not it returns -1. So in your case if it is -1 which means that the passed value was not one of the accepted then do your thing.
Alternatively, you could use a checkbox instead of a text box, and just test if it is checked property is true.
Just try the following:
if (admin == true || admin == false || admin == "true" || admin == "false") {
//if you want to convert -> convert it, and send to server
} else {
//Wrong input
}
(More at here.
This is an equality table for values if you use == instead of ===)
why you don't just check if it's 1, 0, true or false but using logical AND like this:
if(admin != 0 && admin != 1 && admin != "true" && admin != "false"){
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}

Really basic javascript, checking a condition using || (or)

I am very new to JavaScript, and trying to learn using lynda.com.
I'm currently playing around with the if statement.
The code in question:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
if ( value == 2 ) {
alert("You have chosen 2.");
}
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
This is what i want to happen: If the number is NOT 1 or 2, i want JS to execute this piece of code:
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
Apparently this is not the correct way to write it out, and i've tried writing it a bunch of different ways. Can someone show me the correct way, possibly using the else statement?
if ( value != 1 && value != 2) {
alert("Invalid number. Try again.");
}
If you write value != (1||2), the (1||2) will get first evaluated to 1 and then compared to value, so you effectively wrote:
if ( value != 1 ) { [...] }.
This is because the () have a higher predence than !=. You can also read this explanation about operator predence which gives more details.
1
if ( value != 1 && value !=2 ) {
alert("Invalid number. Try again.");
}
2
if ( !(value == 1 || value ==2) ) {
alert("Invalid number. Try again.");
}
3
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
The best way to write this statement would be as follow:
if ( value == 1 )
{
alert("1");
}
else if ( value == 2 )
{
alert("2");
}
else
{
alert("no 1 or 2");
}
The if statement that you are messing on is (1 || 2)
What will happen is it will do a Boolean test and return 1.
it should look like this
if ( value !== 1 && value !== 2 )
{
alert("no 1 or 2");
}
Thanks
As already noted, the best is to separate into two NOT statements,and evaluate both:
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
However, you could also use the if, else if, else pattern to cover yourself against all other inputs (letters, punctuation, whitespace, etc). The else acts as a catch-all at the end:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
Inline statements like: (1 || 2) only evaluate the right hand side of the || if the left hand side is false-y. So what your statement actually is saying is:
if ( value != 1 )
Because 1 evaluates to true.
As most others have pointed out, what you actually want to do is:
if ( value != 1 && value != 2 )
The logic is incorrect. You have to do in this way
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
the (1||2) statement is evaluated as 1 so you are testing if value != 1
have tried writing
if(value != 1 && value != 2)
You have to do it like
if ( value != 1 && value != 2 ) {
alert("Invalid number. Try again.");
}
OR
if (!(value == 1 || value == 2)) {
alert("Invalid number. Try again.");
}
You can use switch as follows
switch(value) {
case 1:
alert("You have chosen 1.");
break;
case 2:
alert("You have chosen 2.");
break;
default:
alert("Invalid number. Try again.");
}
Your problem is here:
if ( value != (1 || 2) )
What ths is doing is checking if "value" is not equal to (1 OR 2), where (1 OR 2) is evaluated first, because it's in the brackets. (1 OR 2) evaluates to 1, since 1 is truthy in javascript. What your code is actually doing is checking if your value is not equal to 1.
What you actually want to do is check if your value is !=1 and that your value is !=2. You do that like this:
if (value !=1 && value !=2) { /* do something */ }
You don't need a clause. You can just use:
else{
}

JavaScript - validate numeric only and within range

I have an asp form which has a number of fields. On submit I want to check, using javascript that a tickbox has been selected and that an 'amount' field in within a given range AND has numbers only. I'm struggling to get it to check all three in one go - at the mometn i have the following:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if (x<5 || x >250)
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
At the moment this is two seperate checks for tick box select and range.
Any ideas appreciated.
Create a function that can do this:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
then call it like so:
function validateForm()
{
if(!validate(document.forms["myForm"]["Amount"].value,
document.forms["myForm"]["agreesubmit"].checked, 5, 250)) {
alert("Please complete all required fields - Amount you wish to save");
return false;
}
}
Try using the isNan(). Tutorial found at http://www.w3schools.com/jsref/jsref_isnan.asp
Something like:
if (isNaN(x) || x < 5 || x > 250))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
Quick note you might be confused about the or/ands, so notice that the x<5 || x >250 is wrapped in () so that it can be partnered with the and numeric condition. Then, finally the whole if wraps the statements.
This will ensure it has numbers only first, then check the number against a range.
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if( String(x).search(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/) != -1
&&( x<5 || x >250 ))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
via http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html

Categories

Resources