My form is validating the two java functions script and if both are true it will continue the form submit. But when i submit it validates only first function validateFormROLLNO() not the second function. Also, when the first function fails it submits the form anyway. I want to submit the form only when the two functions are passed.
first function will check if the roll no = 12 characters.
second function checks if the name is not null.
<body>
<center>
<script type="text/javascript">
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x !=12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validateFormNAME() {
var p = document.forms["myForm"]["student"].value;
if (p =='') {
alert("Name cannot be NULL!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validate(){
return validateFormROLLNO() && validateFormNAME();
}
</script>
<br> <FORM name="myForm" ACTION="insert.jsp" onsubmit="return validate()" METHOD="POST">
Please enter the Rollno and Name you want to INSERT:
<BR> <br>
<b>ISIN :<INPUT TYPE="TEXT" NAME="id"></b>
<BR><BR>
<b> SOURCE :<INPUT TYPE="TEXT" NAME="student"></b>
<br><BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</center>
</body>
</html>
There might be some javascript errors exists on the page, that don't let second function to execute. Please use browser's inspect element to explore it.
document.forms["myForm"]["id"].value you are are checking value of the textbox. Please document.forms["myForm"]["id"].value.length to validate it.
Here is the complete method.
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x.length <12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
else
return true;
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
Related
I am having an issue with the following code:
If you run the following code you get a form with 3 fields: Student ID, Course ID and e-mail. Using javascript i have to check if the student field has 7 characters with two first beeing CS followed by 5 digits. I have to do the same check with the Course ID field but for 5 characters starting with CL followed by 3 digits. The Student ID check works fine but the Course ID does not. From what i see i dont have a mistake ? Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var name = document.forms["mainForm"]["id"].value;
if(name.length != 7) {
alert("Student ID field must be 7 characters");
return false;
}
var csRegex = name.match(/\bCS/);
if(csRegex != "CS") {
alert("Student ID must start with CS prefix");
return false;
}
var digitsRegex = name.match(/[0-9]/g);
if(digitsRegex.length != 5) {
alert("Student ID must start with CS prefix followed by 5 digits");
return false;
}
var courseVar = document.forms["mainForm"]["course"].value;
if(courseVar.length != 5) {
alert("Course ID must be 5 characters");
return false;
}
var clRegex = courseVar.match(/\bCL/);
if(clRegex != "CL") {
alert("Course id must start with CL prefix");
return false;
}
var digitsCourseRegex = courseVar.match(/[0-9]/b);
if(digitsCourseRegex.length != 5) {
alert("Course ID must have 3 digits after CL");
return false;
}
}
</script>
</head>
<body>
<form name="mainForm" onsubmit="return validateForm()">
Student ID:<br>
<input type="text" name="id" maxlength="7" required>
<br>
Course ID:<br>
<input type="text" name="course" maxlength="5" required>
<br>
E-mail:<br>
<input type="email" name="mail" required>
<br><br>
<input type="submit" value="Register">
<input type="reset" value="Reset">
</form>
</body>
</html>
The JS solution is to use a better regular expression to validate the entire string at once:
"CS23444".match(/CS\d{5}/)
adeneo's answer is correct and may be the better actual solution - except it doesn't use JS, it uses HTML5. If he posts an answer that you are OK with, I'd accept that one!
Should var digitsCourseRegex = courseVar.match(/[0-9]/b); be var digitsCourseRegex = courseVar.match(/[0-9]/g);, With the difference being the /b); or the /g);?
<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length
I already checked How to prevent form from being submitted? but it did not help.
I have a register form with some input and a submit button
<script src="formValidation.js"></script>
<script src="md5.js"></script>
<script language="javascript">
function doSomething() {
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation();}
<form name="registration" action="/Arnito_test/Register" method="post" >
<input onClick="return doSomething();" type=submit>
formValidation.js:
function formValidation() {
...
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
return false;
}
...}
If I force this alert, it appears, but the form submits anyway.
the return false should block it, no?
doSomething() needs a return statement. The last line should be:
return formValidation();
Try -
Add "event" as a parameter that doSomething gets
Send it to formValidation
Add event.preventDefault();
function doSomething(event)
{
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation(event);
}
function formValidation(event) {
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
event.preventDefault();
return false;
}
}
I think you should use
<input onSubmit="return doSomething();" type=submit>
When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.
I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>