Why does onsubmit function seem not to execute? - javascript

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.

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 Validation doesnt work in my Spring boot

As i try to do javascript validation but it dosent work on click of submit button
my Js Code : validation.js which is inside resource/static/js/validate.js
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
my jsp code : registration.jsp
<script type="text/javascript" src="/js/validate.js"></script>
</head>
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;">${emailExistError} </font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=pass#1234
spring.jpa.show-sql=true
spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/hotelmgmt
spring.main.allow-bean-definition-overriding=true
server.port = 8090
pls tell where am i missing the point?
You need put <script type="text/javascript" src="/js/validate.js"></script> before close body tag instead of head tag.
Put this line in one line.
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Current code show error "Uncaught SyntaxError: Invalid regular expression: missing /"
I tried reproduce your code, it worked
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;"></font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
I think it would be helpful for you to first simplify the return statements.
The hasError = !false is very confusing.

javascript form validations

I am using javascript validations for required field. Here is my html
<form class="uk-form-stacked" name="myForm" action="<?php echo base_url(); ?>admin/pages/create_service" id="wizard_advanced_form" method="post" enctype="multipart/form-data" onsubmit="return myFunction(this)" novalidate>
<div data-uk-grid-margin="" class="uk-grid">
<div class="uk-width-medium-1-2">
<label for="service_title">Service Title<span class="req">*</span></label>
<input type="text" name="service_title" id="validd" class="md-input" />
<p id="demo"></p>
</div>
</div>
<div class="uk-grid">
<button type="submit" class="md-btn md-btn-primary md-btn-wave-light waves-effect waves-button waves-light" >Submit</button>
</div>
</form>
my javascript is
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
return false;
}
</script>
Now when my input field is empty and i submit form it shows me input not valid that is fine. but even when i fill some textin input then it shows me undefined in place of input not valid instead of submitting form.
please help..
You forgot to add an else where it would return true if the condition is not satisfied.
<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";
document.getElementById("demo").innerHTML = text;
return false;
}
else{
return true;
}
}
</script>
You can use instead:
<html>
<head>
<script>
function valid()
{
var x;
x=document.getElementById(validd).value;
if(x==null || x=="")
{
alert("Please input service title");
document.getElementById(validd).focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return valid()">
<input type="text" name="service_title" id="validd"/>
<button type="submit">Submit</button>
</form>
</body>
</html>`

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

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources