How to validate enter key in Javascript? - 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>

Related

After Javascript Validation page redirect to another page

i have tryed to validate textbox using javascript.when i click on the submit button without inserting values to textbox it's display alert box.but after click on "ok" button , page redirect to payments.php page.how to fix it
<form method="post" action="payments.php" >
First Name : <br />
<input name="name" type="text" class="ed" id="name" /> <br />
E-mail : <br />
<input name="email" type="text" class="ed" id="email" /> <br />
<input name="but" type="submit" value="Confirm" onclick="Validation()" />
</form>
function Validation()
{
if (checkFName()&&checkemail())
{
window.event.returnValue = false;
}
}
function checkFName()
{
var tname = document.getElementById("name").value;
if((tname == null)||(tname == ""))
{
alert("Please Enter your First name");
return false;
}
return true;
}
function checkemail()
{
var email = document.getElementById("email").value;
var ap = email.indexOf("#");
var dp = email.lastIndexOf(".");
if((ap < 1)||(dp-ap < 1)||(dp >= email.length-1))
{
alert("invalid email address");
return false;
}
else
return true;
}
You need to change the CONFIRM button type to "button":
<input name="but" type="button" value="Confirm" onclick="Validation()" />
Give your form a name:
<form name="frm" method="post" action="payments.php">
then in your Validation() function, if your form passes validation, you can do the following:
function Validation()
{
if (checkFName()&&checkemail())
{
document.forms["frm"].submit();
}
}

Validate Numbers 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
// ]]

Can't get .focus() to focus on an input with an id in Chrome, Safari, and FF

I am having issues with a code I am using to check email validity before sending it off to a database. I have a javascript code that checks the email in the following way:
See if the first email is a valid email address
See if the two email fields match
Here is the relevant parts of the form:
<form action="URLGOESHERE" method="post" name="someName" onSubmit="return validation();" id="formId">
<section class="sectionHeader">
<h2>Contact Information</h2>
<span class="important">*Required Fields</span>
</section>
<section id="contactInfo">
<fieldset>
<legend>Contact Information</legend>
<div id="contact">
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>First Name:</label>
<input type="text" name="firstName" class="imp" size="20" maxlength="25" placeholder="John">
</div>
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>Last Name:</label>
<input type="text" name="lastName" class="imp" size="20" maxlength="25" placeholder="Smith">
</div>
<div class="inputGroupSL">
<span class="left"><label for="org">Company/Group Name:</label></span>
<input type="text" name="org" size="30" maxlength="50" placeholder="Auburn University">
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email"><span class="important">*</span>Email:</label></span>
<input name='email' id='email' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com" />
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email2"><span class="important">*</span>Re-type Email:</label></span>
<input name='email2' id='email2' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com"/>
</div>
<div id="phoneGroup">
<span class="left"><span class="important">*</span>Phone #:</span>
<input name='phone' type='text' class="imp" id="phone" size='12' maxlength='20' placeholder="xxx-xxx-xxxx" />
</div>
<div id="extGroup">
<span class="left">Ext:</span>
<input name='ext' type='text' id="ext" size='12' maxlength='6' placeholder="xxxx" />
</div>
</div>
</fieldset>
</section>
And here is my code that runs onSubmit:
var reEMail=/^\w[\w\-\.]+\#\w[\w\-]+(\.[\w\-]+)+$/;
function validation() {
if (!checkImportant()) {
alert("Please enter information in all fields marked important.");
return false;
}
if (!checkAttendees())
return false;
if (!checkEmail($('#email'),$('#email2')))
return false;
return true;
}
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
function checkAttendees() {
total = 0 + Number($('#numAttend').val());
parts = 0 + Number($('#8').val()) + 0 + Number($('#12').val()) + 0 + Number($('#16').val()) + 0 + Number($('#19').val()) + 0 + Number($('#26').val()) + 0 + Number($('#26').val()) + 0 + Number($('#55').val());
count = 0;
if (total != (parts)) {
alert('Please check to ensure you have entered the correct number of participants.');
count++;
if (count%2 == 0) {
$('#numAttend').focus();
return false;
}
else {
$('#8').focus();
return false;
}
}
return true;
}
function checkEmail(email,email2) {
if (goodEMail2(email)) {
if (email.val() != email2.val()) {
alert("Please check to make sure your email address is correct in both fields!");
email2.focus();
return false;
}
else return true;
}
else {
alert("Please input a valid email address");
setTimeout(function(){
$('#email').focus();
}, 100);
email.select();
return false;
}
return false;
}
function goodEMail2(field) {
return _checkIt2(reEMail, field);
}
function _checkIt2(re, field){
if (!re.test(field.val())) {
field.select();
field.focus();
return false;
}
else return true;
}
As you can see in my main if else statement of my checkEmail function I am having to use setTimeout to delay the focusing on the email field. If I take out the setTimeout, the page will not focus on the element. However, if I take out the setTimeout and change the specified element to the second email field, it works.
The only exception to this is in IE10 (to my testing in FF, Chrome, Safari, and IE10).
I don't really want to use this work around and I don't understand why I need to. Can anyone give me some ideas or answers?
Thanks!
EDIT: Can't seem to get my hack to work now. I'm not sure what it was doing before... so now focus() doesn't work at all on that particular element.
changing:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
to:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if(important[i].value == "") { // drop the jQuery reference, not needed
important[i].focus(); // drop the jQuery reference, not needed
return false;
}
}
return true;
}
worked for me in Chrome

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>

Unable to Submit the Form using submit() in a javascript method

Unable to Submit the Form using submit method in the javascript method & onclick event
on the button element even tried using the onsubmit event in the form tag.
Need the reason for not submitting the details.You can copy the code & run it for more
clarity on it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">`enter code here`
function validateForm(form) {
if (validateNames(form['hallticket'], form['hallticket_help']) && validateNames(form['firstname'], form['firstname_help'])) {
form.submit();// Form is not getting submit
}
else {
alert("Please Enter the Required Fields");
}
}
function validateNonEmpty(inputField, helpText) {
return validateRegex(/.+/, inputField.value, helpText, "please Enter a value");
}
function validateRegex(regex, input, helpText, helpMessage) {
if (!regex.test(input)) {
//Data is mismatched
if (helpText != null) {
helpText.innerHTML = helpMessage;
return false;
}
}
else {
if (helpText != null)
//data is matched
helpText.innerHTML = "";
return true;
}
}
function validateHallticket(inputField, helpText) {
if (!validateNonEmpty(inputField, helpText)) {
return false;
}
else
return validateRegex(/^\d{2}K91A\d{4}$/, inputField.value, helpText, "Enter valid Hallticket");
}
function validateNames(inputField, helpText) {
// see that input data is non empty
if (!validateNonEmpty(inputField, helpText)) {
return false;
}
else
return validateRegex(/.+/, inputField.value, helpText, "Please Enter only Alphabets");
}
</script>
<link rel="StyleSheet" href="test1.css" type="text/css"></link>
</head>
<body>
<center>
<font face="Arabic Transparent" size="6" color="Teal">4cUBeS College</font>
</center>
<br></br>
<br></br>
<form method="post" action="servlet.do" name="myform">
<table border="1">
<tr>
<td>
HallTicket:
<input type="text" name="hallticket" id="hallticket"
onblur="validateHallticket(this,document.getElementById('hallticket_help'))"></input>
<span id="hallticket_help" class="helpcss"> </span>
</td>
</tr>
<tr>
<td>
FirstName:
<input type="text" name="firstname" id="firstname"
onblur="validateNames(this,document.getElementById('firstname_help'))"></input>
<span id="firstname_help" class="helpcss"> </span>
</td>
<td>
LastName:
<input type="text" name="lastname" id="lastname"
onblur="validateNames(this,document.getElementById('lastname_help'))"></input>
<span id="lastname_help" class="helpcss"> </span>
</td>
</tr>
</table>
<center>
<input type="button" value="SUBMIT" onclick="validatForm(this.form)"></input>
</center>
</form>
</body>
</html>
Please check your spelling of the function called in onclick, its misspelled as 'validatForm' instead of 'validateForm'
This fixes many issues
DEMO
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function validateNonEmpty(inputField, helpTextId) {
var helpText = document.getElementById(helpTextId);
return validateRegex(/.+/, inputField.value, helpText, "please Enter a value");
}
function validateRegex(regex, input, helpText, helpMessage) {
if (regex.test(input)) {
if (helpText != null) {
helpText.innerHTML = "";
}
return true;
}
//Data is mismatched
if (helpText != null) {
helpText.innerHTML = helpMessage;
}
return false;
}
function validateHallticket(inputField, helpText) {
if (!validateNonEmpty(inputField, helpText)) {
return false;
}
return validateRegex(/^\d{2}K91A\d{4}$/, inputField.value, helpText, "Enter valid Hallticket");
}
function validateNames(inputField, helpText) {
// see that input data is non empty
if (!validateNonEmpty(inputField, helpText)) {
return false;
}
return validateRegex(/.+/, inputField.value, helpText, "Please Enter only Alphabets");
}
window.onload=function() {
document.getElementById("myform").onsubmit=function() {
if (validateNames(this['hallticket'], 'hallticket_help') &&
validateNames(this['firstname'], 'firstname_help') &&
validateNames(this['lastname'], 'lastname_help')) {
return true;
}
alert("Please Enter the Required Fields");
return false; // cancel submit
}
}
</script>
<link rel="StyleSheet" href="test1.css" type="text/css"></link>
</head>
<body>
<center>
<font face="Arabic Transparent" size="6" color="Teal">4cUBeS College</font>
</center>
<br></br>
<br></br>
<form method="post" action="servlet.do" name="myform" id="myform">
<table border="1">
<tr>
<td>
HallTicket:
<input type="text" name="hallticket" id="hallticket"
onblur="validateHallticket(this,'hallticket_help')" />
<span id="hallticket_help" class="helpcss"> </span>
</td>
</tr>
<tr>
<td>
FirstName:
<input type="text" name="firstname" id="firstname"
onblur="validateNames(this,'firstname_help')" />
<span id="firstname_help" class="helpcss"> </span>
</td>
<td>
LastName:
<input type="text" name="lastname" id="lastname"
onblur="validateNames(this,'lastname_help')" />
<span id="lastname_help" class="helpcss"> </span>
</td>
</tr>
</table>
<center>
<input type="submit" value="SUBMIT" />
</center>
</form>
</body>
</html>
Apart of the issues already found in you code there is one more.
Your button submit input tag is:
<input type="button" value="SUBMIT" onclick="validatForm(this.form)"></input>
And must be:
<input type="submit" value="SUBMIT" onclick="validateForm(this.form)"/>

Categories

Resources