Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/
Related
Need validation for full name(first name/last name - 1 input field). I'm new in this sphere and can't formulate the right syntax maybe will work with a regular expression too
<form name="myForm" action="#" id="form" onsubmit="return validateForm()" method="POST">
<div class="field"><span class="input"><i class="fas fa-user-alt"></i>
<input type="text" id="name" name="Fullname" placeholder="Full Name" >
</span>
function validateForm() {
var name= document.getElementById('name').value;
var x = name.indexOf(" ");
var fname = name.substring(0, x);
var lname = name.substring(x).trim();
if ( 17 < fname.value.length < 5 || 4 > lname.value.length > 17 || x.value.length != 1) {
alert("try again")
return false;
}
alert("OK")
return true;
}
The field (1 field) should contain 2 words which should be from 3 to 20 symbols.
EDIT:It seems work..finally!
function input (name) {
let fullNameArr = name.split('')
const space = ' '
let firstName = ''
if (fullNameArr.includes(space)) {
for (let i = 0; i < fullNameArr.length; i++) {
if (!firstName.includes(space)) {
firstName += fullNameArr[i]
}
}
}
firstName = fullNameArr.splice(0, firstName.length)
const lastName = fullNameArr
if (firstName.length > 3 && firstName.length <= 21 && lastName.length >= 3 && lastName.length <= 20 && lastName.includes(space) === false) {
console.log(firstName)
console.log(lastName)
} else {
console.log('Invalid Name')
return false
}
}
input('Todor Markov')
Your model makes several assumptions about names. Having first name and last name as separate input boxes is typically done to remove this barrier.
From a UX standpoint, if you were not going to have separate fields, you'd need some validation with a tooltip that checked if the user has more than one space that alerts them they must type FirstName LastName.
From a regex validation view, here's a catch all to ensure it's valid.
/^[a-z ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.")
No numbers, but allow letters and the special characters ,.'-.
How would you make an if/else statement loop back to the beginning to get user information?
This is the code I got so far:
var age = prompt("Please enter your age");
if(age == 21 ) {
alert("Happy 21st Birthday!");
} else if (age > 21 ) {
alert("You are old");
} else {
alert("Please enter an age");
}
I'm trying to make it go back to the beginning to make the user enter information.
var age = '';
while(age == '' || age == 'ok'){
age = prompt("Please enter your age");
if($.isNumeric(age) === false){
continue;
}
if(age == 21 ){
alert("Happy 21st Birthday!");
continue;
}
if (age > 21 ){
alert("You are old");
continue;
}
if (age < 21){
alert("You are too young to be in this bar!");
}
}
for (let age = prompt('Please enter your age'); ;) {
if (age == 21) {
alert('Happy 21st Birthday!');
break;
} else if (age > 21) {
alert('You are old');
break;
} else {
age = prompt('Please enter your age');
}
}
You separate validation logic from the user input logic.
If this is console app then you would place a loop around the prompt and then validate the user age, if the age is valid break out of the loop otherwise let the loop continue.
On a web page you would wrap it in a function and based on the result manipulate the view based on if the age is correct or not. So you would perhaps show an error message if the age is invalid or go to the next page if the age is valid.
You should wrap the if statements which make up the validation logic in into a function perhaps validateAge that returns true or false, that way no matter what you implement you can use the same method.
Working off of #wallyk's suggestion using a while loop yields this example:
var age = false;
while (!age) {
age = prompt("Please enter your age");
if (age == 21) {
alert("Happy 21st Birthday!");
} else if (age > 21) {
alert("You are old");
} else if (!!age && age < 21) {
alert("You are young");
} else {
alert("Please enter an age");
age = false;
}
}
It will keep looping until you type a valid number answer. I also added in a check to see if the user input an age under 21, since I'm guessing you don't want to keep looping forever if the user is under 21 (or keep looping until they turn 21) but that part can easily be removed if you want.
Hi what am I doing wrong with this if statement? Ive tried making the second one and else if and the last one an else as well but cant get the alerts to respond properly.
prompt("Please enter a number");
if(x < 100) {
alert("variable is less 100")
}
if(x == 100) {
alert("variable is equal to 100!")
}
if(x > 100) {
alert("variable was greater than 100")
}
thanks!
You are missing an assignment to variable x.
var x = prompt("Please enter a number");
//^^^^^
Then you could use parseInt to get a integer number from the string
x = parseInt(x, 10);
Basically, I want to change a person input from 0######### to (0#)########, the event im using is onblur
function numberChange(){
var check = document.getElementById("number").value;
var regCheck = /^[0-9]+$/;
if (check != 10 || !regCheck)
{
alert("Please input your 10 digit mobile number")
return false;
}
else if (check == 10 || regCheck)
{
return true;
}
}
Your regCheck should be ^\(0\d\)\d{8}$
Demo
Update :
This regex validates the number of characters, you can omit length check in your code :
function numberChange(){
var check = document.getElementById("number").value;
var re = new RegExp(/^\(0\d\)\d{8}$/);
if (re.test(check)) {
return true;
}
else {
alert("Please input your 10 digit mobile number")
return false;
}
}
This will check for 10 digits, first number is zero, and that all inputs are digits. Once all of that passes the code will add the '(' & ')' to it. This approach gives specific errors depending on how the user incorrectly entered the number.
<html>
<body>
Phone number: <input type="text" id="number" onblur="checkNumber()">
<script>
function checkNumber() {
var x = document.getElementById("number").value;
// Check for 10 digits.
if(x.length != 10) {
alert('The number must be 10 digits.');
return false;
}
// Make sure the first digit is 0.
if(x.charAt(0) != 0) {
alert('The first digit must be 0.');
return false;
}
// Make sure all digits are numbers and not characters.
if(isNaN(x) == true) {
alert('All digits must be numbers.');
return false;
}
// If here then everything else passed so add the '(' and ')' to the number.
document.getElementById("number").value = '(0' + x.charAt(1) + ')' + x.substring(2, 10);
}
</script>
</body>
</html>
I am currently using Google maps and attempting to use input validation. I require the user to use a number between 0 and 20 to set as a zoom on my location.
Below is the code I am using. The first if statement works perfectly for any number over 20 but the second does not work when I use numbers like 0 and -1 (for instance.)
Any suggestions for fixing this?
function inputIsValid() {
console.log("Inside inputIsValid function");
//Check for Above 20
if (document.getElementById("txtZoom").value > 20) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
//Check for Number below 0
if (document.getElementById("txtZoom").value < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}
}
The problem is you nested the second check within the first, so it will never be reached. Try this:
function inputIsValid() {
var zoomValue = document.getElementById("txtZoom").value;
if (zoomValue > 20 || zoomValue < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}
function inputIsValid() {
$value = document.getElementById("txtZoom").value;
if (($value < 0) && ($value > 20)) {
alert("Please enter a value between 0 and 20");
return false;
}