Below is my simple jsp form where i need to validate the whether the branch number is empty before doing the ajax call.
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" onsubmit="return validateForm()" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit" onclick="addData(); return false;"></input>
</td>
</form>
</table>
</div>
</body>
Below is my javascript
function validateForm(form) {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return false;
}
}
If i remove the return false; in the submit input it does populate alert form the branch input but it still calls the addData(). How to validate the form before call the function addData().
when you click on your submit button, your function addData will be called first and then your validateForm function. If I understood right, you want to validate the form on submission and then call your addData if everything is okay! In this case you can do this:
<body>
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form name="orderform" id="orderform" onsubmit="return validateForm();" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" >
</td>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div>
</body>
and the JS:
function validateForm() {
var x = document.forms["orderform"]["branch"].value;
if (x == "") {
alert("You must select a valid Branch branch");
return;
} else {
addData();
}
}
function addData() {
// di stuff here with your data
alert('Everything is okay do stuff');
}
Make just one function that is called on submit event. Inside that function call another one like your validateForm(). If you discover that something is wrong while validating, call event.preventDefault()/event.returnValue = false or just return false as you already know. Also if you want branch numbers to be numeric, use isNumeric function instead of just checking if it is an empty string.
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isDataValid(data) {
// your checks...
if (!isNumeric(data.branch)) return false;
return true;
}
function addData() {
var e = event || window.event;
var data = {};
data.branch = document.forms["orderform"]["branch"].value;
// other data
// ...
if(!isDataValid(data)) {
console.log("Data is invalid! The submit will not happen!");
e.preventDefault();
} else {
// remove this else-branch later to make submit happen because the data in this case is valid
console.log("Data is valid! The submit will happen!");
e.preventDefault();
}
}
document.getElementById("orderform").addEventListener('submit', addData, false);
<div id = "divOrderuserinputContainer">
<table align="center" id="table">
<form id="orderform" method="POST">
<td class="label">Branch Number:
<input type="text" name="branch" ></input>
</td>
<td>
<input type="submit" value="submit"></input>
</td>
</form>
</table>
</div>
PS don't forget to handle cross-browserness addEventListener/attachEvent, preventDefault/returnValue = false etc. Also you could collect errors inside isDataValid and show them later to users in case they inserted something incorrectly.
Related
I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance
Nvm it only works with addEventListener
I have a page where user prints data and then click button submit.
<form id="myForm" action="/validate-configuration" _method="post" method="post" enctype="multipart/form-data"
onsubmit="return validateForm(this);">
<table>
...
<tr>
<td></td>
<input
type="submit"
value="Obfuscate"
onclick="return doConfirm('<%=messageSource.getMessage("message.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {});"
/>
</td>
<td> </td>
</tr>
</table>
</form>
<div id="confirmBox" class="modal">
<div class="modal-content">
<div class="message"></div>
<button type="button" class="yes">Yes</button>
<button type="button" class="no">No</button>
</div>
</div>
When a user clicks on submit first appear to confirm window. But I want to rich next behaviour. When something is not inputted first works validation function and after all input fields were completed appear to confirm button after click on submit button.
function validateForm(form) {
return validateConfigurationSelect(form) && validateDBCredentials(form) && validateSalt(form);
}
function doConfirm(msg, yesFn, noFn) {
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Answer:
make function doConfirm like this:
function doConfirm(msg, yesFn, noFn, validationFunc) {
if (validationFunc) {
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
}
and in hmtl markup replace type of button form "submit" to "button" and add function:
input type="button" value="Obfuscate" onclick="
doConfirm('<%=messageSource.getMessage("message.dialog.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {
},
validateForm()
);"/>
Also note that validateForm() should return boolean value.
Well, first of all, you should not validate on the client (with Javascript) but on the server (with Java). Validating in javascript is bad because it is easy to by pass it.
BUT, to answer your question. Change your code into:
<input type="button"
value="Obfuscate"
onclick="if (validateForm()) { return doConfirm('<%=messageSource.getMessage("message.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {}); } else { showErrors() } "
/>
You don't need to pass the "form" argument in validateForm() because you can retrieve the values with document.getElementBy("") etc.
So to summarize:
user presses Save button (which is not submit type but just button type button)
validateForm() is called
if true then call doConfirm(), if OK button then $('#myForm').submit();
if false then display some errors
I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">
Javascript gives error window, but it won't stop the form submission. I'm stumped at this point and can't find an exact answer. Here is the code, thanks:
function newNameValidate() {
var x = document.forms["checkIn"]["newName"].value;
if (x==null || x=="") {
alert("Tech name must be filled out");
return false;
}
return true;
}
Here is the HTML:
<form name="checkIn" onsubmit="newNameValidate(checkIn)" action="check_in_complete.php" method="POST">
<input type ="submit" class="input" value="CHECK IN">
You must return the value of the function, onclick="return foo();"
As others have said, you need to return the value returned from the function, but a better option is to use unobtrusive JavaScript:
<form name="checkIn" action="check_in_complete.php" method="POST">
Script:
window.onload = function() {
document.forms["checkIn"].onsubmit = newNameValidate;
}
It can be done like:
<form name="checkIn" id="checkIn" action="check_in_complete.php" method="POST">
<input type ="button" class="input" value="CHECK IN" onclick="newNameValidate()">
</form>
<script>
function newNameValidate() {
var x = document.forms["checkIn"]["newName"].value;
if (x==null || x=="") {
alert("Tech name must be filled out");
return false;
}else{
checkIn.submit();
}
}
</script>
This is code which should perform a submission on a form, but it doesn't do the submission:
<script>
function validate(){
var formm = document.getElementById('form_first');
var basar1=document.form_first.basar1;
var basar2=document.form_first.basar2;
if(basar1.checked == 1 && basar2.checked == 1){
alert('Please ckeck only one of them') ;
}
else{
formm.submit();
}
}
</script>
And this is my HTML page:
<form action="#" method="post" name="form_first" id="form_first" >
<tr id="row_ques">
<td width="200">aaaaa</td>
<td width="113"><input type="checkbox" name="basar1" value="aaaa" /></td>
<td width="113"><input type="checkbox" name="basar2" value="bbbb" /></td>
</tr>
<input type="button" onclick="validate();" value="Save" name="btn_first" id="btn_first" />
</form>
the problem is that the form isn't submitted if validation checked correctlly
Posting to hash "#" doesn't trigger a page load. Posting to "" will load the page with the post data.
<form action="" method="post" name="form_first" id="form_first" >
<tr id="row_ques">
<td width="200">aaaaa</td>
<td width="113"><input type="checkbox" name="basar1" value="aaaa" /></td>
<td width="113"><input type="checkbox" name="basar2" value="bbbb" /></td>
</tr>
<input type="button" onclick="validate();" value="Save" name="btn_first" id="btn_first" />
</form>
Cleaned up JS:
function validate(){
var formm = document.getElementById('form_first');
if(formm.basar1.checked && formm.basar2.checked ){
alert('Please ckeck only one of them');
}else{
formm.submit();
}
}
You can use onSubmit function to validate the form
<form action="/feedback" method="post" name="form_first"
onSubmit="return validate()">
<!-- write your form conent -->
</form>
function validate(){
//validation
if (failed) {
// return false will cancel the form submission
return false;
}
// If everything goes well, proceed the form submission
return true;
}
change these lines
var basar1=document.form_first.basar1;
var basar2=document.form_first.basar2;
to
var basar1=formm.getElementById('basar1');
var basar2=formm.getElementById('basar1');
and you should be through