Validate Numbers Javascript - javascript

I have written the code so far and came up with this. I have to
Make sure the user input numbers into the text boxes and I was given errors using the Xhtml format, one, the '&&' sign gave me errors and due to online help, I was told I needed to use //
As I student learning Javascript I have no idea what this is or means, but as I placed it there, I was given more errors and my code crashed up after the javascript was added.
Thanks for the help in advance
<head>
<script type = 'text/javascript'>
// <![CDATA[
$('#submit').click(function(){
validateRange();
validateRa();
})
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
// ]]
</script>
<title>Account Lookup</title>
</head>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance"/></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>

EDITED
try using this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
validateRange();
validateRa();
});
});
function validateRange() {
var txtVal = document.getElementById("CustomerID").value;
var txtVal1=parseInt(txtVal);
if (txtVal1 >= 3000 && txtVal1 <= 3999) {
return true;
}
else {
alert('Please enter a number between 3000-3999');
return false;
}
}
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
}
</script>
<html>
<title>Account Lookup</title>
<body>
<h1> Please Provide Your Information</h1>
<p><input type="text" id="AcctNo" value="Account Number"/></p>
<p><input type="text" id="CustomerID" value="CustomerID" onchange="validateRange()"/></p>
<p><input type="text" name="Type" value="Account Type" onchange="validateRange()"/></p>
<p><input type="text" name="balance" value="Balance" /></p>
<p class="submit" />
<input type="submit" name="commit" value="Submit" id="submit" /><button type="reset" value="Clear">Clear</button></p>
</body>
</html>

BTW the function validateRa missing the closing curly braces you need to add } before // ]]
function validateRa() {
var txtVal1 = document.getElementById("AcctNo").value;
var txtVal2=parseInt(txtVal1);
if (txtVal2 >= 90000 && txtVal2 <= 99999) {
return true;
}
else {
alert('Please enter a number between 90000-99999');
return false;
}
} //<= this is missing in your code
// ]]

Related

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

JavaScript username and password verification

I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd

How to validate enter key in Javascript?

I have following script running on my site. Users have to enter "testnumber" which is 10 character long. There is a length check validation. When users click on submit button my script does work smoothly.
But the problem is that when users press the enter key instead of mouse click, it does not warn the users. How can i change it so that when the users press the enter key this script will give the same message as they click on submit button?
<script type="text/javascript">
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function formvalidation(form) {
var isSubmitting = false;
var value = document.getElementById('testnumber').value;
if (value.length == 10) {
if (isNumber(value)) {
isSubmitting = true;
}
}
if (isSubmitting) {
form.submit();
}
else {
alert('testnumber must be at least 10 character.');
return false;
}
}
</script>
This is the part of the html code:
<tr>
<td align="center">
<label>
<div align="left">
<span class="text7"><strong>enter testnumber:</strong></span>
<input name="testnumber" type="text" id="testnumber" size="50" value="<%=(testnumber)%>" />
<input name="search" id="search" type="button" class="normalmail" value="Search" onclick="formvalidation(frmSearch);" />
</div>
</label>
</td>
</tr>
Hope this will help
<from onsubmit="return formvalidation()">
<tr>
<td align="center">
<label>
<div align="left">
<span class="text7"><strong>enter testnumber:</strong></span>
<input name="testnumber" type="text" id="testnumber" size="50" value="<%=(testnumber)%>" />
<input name="search" id="search" type="button" class="normalmail" value="Search" onclick="formvalidation(frmSearch);" />
</div>
</label>
</td>
<!-- </tr></tr> -->
</form>
Your Script
<script type="text/javascript">
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function formvalidation() {
var isSubmitting = false;
var value = document.getElementById('testnumber').value;
if (value.length > 10 && value.length < 10) {
alert('testnumber must be at least 10 character.');
return false
}
else if (isSubmitting) {
return true
}
else {
return false;
}
}
</script>

How to focus cursor on form element?

I want to add cursor after empty input into form element. Where first empty form are.
With this goal I tryed to add this.focus(); into validate() function. But this wasn't succeeded.
And second point - how to set cursor after emerges page at brovser to first form element. I tryed with this target onLoad(); method into body. But this wasn't succeeded.
Code:
<html>
<head>
<title>Form with check</title>
<script>
function validate() {
if(document.form1.yourname.value.length < 1) {
alert("Enter your name, please");
this.focus();
return false;
}
if(document.form1.adress.value.length < 3) {
alert("Enter your adress, please");
this.focus();
return false;
}
if(document.form1.phone.value.length < 3) {
alert("Enter your phone number, please");
this.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Form with check</h1>
<p>Input all data. When button Submit pushed data will be sent as message.</p>
<form name="form1" action="mailto:user#host.com" enctype="text/plain"
onSubmit="validate();">
<p><b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p><b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p><b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="SUBMIT" value="Submit">
</form>
onLoad();
</body>
</html>
Question:
How to add this functionality to form?
didn't you forget to do
onSubmit="return validate();" ?
Replace this.focus() with document.form1.yourname.focus();
Here is the re-worked code:
<html>
<head>
<title>Form with check</title>
<script>
function validate() {
if(document.form1.yourname.value.length < 1) {
alert("Enter your name, please");
document.form1.yourname.focus();
return false;
}
if(document.form1.adress.value.length < 3) {
alert("Enter your adress, please");
document.form1.adress.focus();
return false;
}
if(document.form1.phone.value.length < 3) {
alert("Enter your phone number, please");
document.form1.phone.focus();
return false;
}
document.getElementById("ff").submit();
return true;
}
</script>
</head>
<body >
<h1>Form with check</h1>
<p>Input all data. When button Submit pushed data will be sent as message.</p>
<form id="ff" name="form1" action="mailto:user#host.com" enctype="text/plain"
>
<p><b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p><b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p><b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>
And the Working DEMO too
onSubmit="validate();"
In the context of your validate function this will be the global window object.
To handle the form in the function, based on your code, you can call it manually using document.form1 or by id (or other selector), or you can send the form to the function:
<script>
function validate(sender) {
if(sender.yourname.value.length < 1) {
alert("Enter your name, please");
sender.focus();
return false;
}
if(sender.adress.value.length < 3) {
alert("Enter your adress, please");
sender.focus();
return false;
}
if(sender.phone.value.length < 3) {
alert("Enter your phone number, please");
sender.focus();
return false;
}
return true;
}
</script>
<form name="form1" action="mailto:user#host.com" enctype="text/plain" onSubmit="validate(this);">
<p>
<b>Name:</b><input type="text" length="20" name="yourname">
</p>
<p>
<b>Adress:</b><input type="text" length="20" name="adress">
</p>
<p>
<b>Phone:</b><input type="text" length="20" name="phone">
</p>
<input type="SUBMIT" value="Submit">
</form>

Why does onsubmit function seem not to execute?

I cannot figure out what I'm doing wrong. validateForm() does not seem to execute from an onsubmit. Here is validateForm()
function validateForm() {
var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);
alert(amt);
if (amt == false)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}
function IsNumeric(strString)
{
// check for valid numeric strings
var strValidChars = "0123456789.";
var strChar;
var blnResult = true;
if (strString.length == 0) return false;
// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
if (0 > parseFloat(strString))
{
return false;
}
else
{
return blnResult;
}
}
Here is the form with onsubmit:
<script type="text/javascript" language="JavaScript1.2">
document.write('<form name="InvGenPayDonation" action="'+PostURL+'" onsubmit="return validateForm();" method="POST">');
</script>
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
</form>
Your biggest issue is that you don't have the right form name (or the right field name for that matter) in your validation code.
var amt = IsNumeric(document.forms["InvGenPay"]["Amount"].value);
vs
'<form name="InvGenPayDonation" action="'+PostURL+'"
Full, working code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Sampe file</title>
<script>
function validateForm() {
// Badly named variable, since this is actually a boolean of 'IsNumeric'
var amt = IsNumeric(document.forms["InvGenPayDonation"]["DonationAmount"].value);
// Can be simplified as simply:
//return amt;
alert('Amt = ' + amt);
if (!amt)
{
alert("placeholder to avoid scrolling.");
return false;
}
else
{
return true;
}
}
function IsNumeric(n) {
// Shamelessly stolen from:
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
return !isNaN(parseFloat(n)) && isFinite(n);
}
</script>
<body>
<form name="InvGenPayDonation" action="#"
onsubmit="return validateForm();"
method=POST>
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
<script>
// Assigned for testing purposes
var PostURL = "#"
document.forms.InvGenPayDonation.action = PostURL;
</script>
</form>
</body>
</html>
You cannot have un-escaped newlines in a JavaScript string. Check your JavaScript console, you are probably getting a syntax error. That error is why the onsubmit is not running.
Also, as suggested, do not use document.write, just write the form normally in HTML, and use JavaScript to add just the POST url.
<form name="InvGenPayDonation" onsubmit="return validateForm();" method="POST">
<input type='text' name='DonationAmount' value="0.00">
In honor of <span style="color: #FF0000"><br />
<input type='text' name='TransDesc' id='TransDesc' value="" >
<input type="submit" value="Next">
</form>
<script type="text/javascript">
document.forms.InvGenPayDonation.action = PostURL;
</script>
P.S. As Jeremy J Starcher pointed out, your form name is wrong inside validateForm.

Categories

Resources