I wrote a java script code in a JSP page,But when i try to submit the Page, my javascript validation code is not getting fired,Could any one help me what went wrong?
Here My Code:
<html>
<center><h3>Employee Absent Report</h3></center>
<head>
<script language="javascript" type="text/javascript">
function onFormSubmit(){
var countErrors = 0;
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form" action="FormServlet" method="get" onsubmit="return onFormSubmit(); ">
<center>
<div id="formErrors" class="error"></div>
FromDate:
<input type="text" name="startdate" id="startdate"/>
<div id="divStartDate"></div>
<br>
ToDate:
<input type="text" name="todate" id="todate"/>
<div id="divExpiryDate"> </div>
<br>
<input type="submit" value="submit"/>
</center>
</form>
</body>
</html>
is there a method "IsEmpty" in javascript? I think that's the problem. If you have that defined in some other place, try running your code in Firefox and watch Error Console for errors.
Looks like a logical error to me. Try replacing this:
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
with:
if (endDt.length==0) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt.length==0) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Do the validation this way
if (endDt === "") {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt === "" ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Hope this helps!
this is the working modified code
<script>
function onFormSubmit(event){
var countErrors = 0;
event.preventDefault();
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if ( IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
eFlag = true ;
}
if (IsEmpty(strDt)==true ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
eFlag = true;
}
if(eFlag)
{
return false;
}
return true;
}
function IsEmpty(input)
{
if(input.replace(/^\s+|\s+$/g,"") === "") {
return true;
}
return false;
}
Related
I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation Form</title>
<script type="text/javascript">
function validate()
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var atposition=email_str.indexOf("#");
var dotposition=email_str.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address")
return false
}
if ((!document.getElementById("a").checked)&&(!document.getElementById("b").checked))
{
alert("no button is selected");
return false
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length)
return alert("No box is checked");
var group2 = document.getElementById.dd;
var index_opt = group2.options[group2.selectedIndex].value;
if(index_opt==Select)
{
alert("select course")
return false
}
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name="my_form" onsubmit="validate()">
<strong>Name:   </strong>
<input type=text name=name><br/>
<strong>Password:   </strong>
<input type=password name=pwd><br/>
<strong>Retype Password:   </strong>
<input type=password name=repwd><br/>
<strong>Age:    </strong>
<input type=text name=age><br/>
<strong>Phone No:    </strong>
<input tupe= text name=ph><br/>
<strong>Email:    </strong>
<input type=text name=email><br/><br/>
<strong>Sex:    </strong>
<input type= "radio" name="gender" id="a" value="Male">Male    
<input type= "radio" name="gender" id="b" value="Female">Female    <br/><br/><br/>
<strong>Hobby:</strong>
<input type="checkbox"name= "hobby" id="1" value="singning">Singning<br/>
<input type="checkbox"name= "hobby" id="2" value="reading">Reading<br/>
<input type="checkbox"name= "hobby" id="3" value="tv">TV<br/>
<br/>
<strong>Country</strong>
<select name="mymenu" id="dd">
<option value ="Select">Select</option>
<option value ="India">India</option>
<option value ="China">China</option>
<option value ="SriLanka">SriLanka</option>
</select>
<input type="submit" value=Submit>
<input type="reset" value=Reset><br/>
</form>
</body>
</html>
The code doesn't validate from the radio button on wards. but if i run the radio button code and the other validation codes after the radio button code it works and when compiled in a single form it doesn't works. the drop down menu validation doesn't works at all. please help me. Thanks in advance.
It's not a problem with your radio button check. In your code, you can use one variable like x, that's the problem. kindly refer below code :
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
That above code x variable doesn't declare and doesn't assign any where in your code. So that line error occurred and terminated.
You change this x to email_str, As per your code should be like below,
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email_str.length)
It's working fine.
First of all you should change your on submit Event like below
<form name="my_form" onsubmit="return validate(this.form)">
Here your complete Javascript
<script type="text/javascript">
function validate(form)
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var email = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
var gender=document.my_form.gender.value;
if((gender=="null")||(gender=="")){
alert("Please Select Gender");
return false;
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length){
alert("No box is checked");
return false;
}
var country=document.my_form.mymenu.value;
if(country=='Select'){
alert("You must Select your Country");
return false;
}
}
</script>
I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.
I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number .
for example : "Laksda Adisucipto street, no 22A."
but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"
i'm using Twitter Bootstrap and Validator.js
here's my code
HTML :
<div class="form-group col-md-12">
<label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
<textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
<span class="help-block with-errors"></span>
</div>
JS :
<script>
$('#address').change(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(($('#').value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
} );
Try this
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
you can check it here: http://jsfiddle.net/oa6eewck/
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.
So better follow the expression follows :
$('#address').blur(function()
{
var hasNumber = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
if ( hasNumber) {
return true;
} else {
alert("message");
return false;
}
});
$('#address').on('change', function () {
var hasNumber = this.value.match(/\d/);
var isAlfa = this.value.match(/^[0-9a-zA-Z]+$/);
if ( hasNumber && isAlfa ) {
return true;
} else {
alert("message");
return false;
}
});
FIDDLE
adeneo's solution is right. but I think isAlfa should have following value
var isAlfa = this.value.match(/^[A-Za-z\d(-.,) ]+/);
i need to make an html page when you put a password to. whenever the user insert the correct password he will be sent out to a website. if the user won't insert the correct password he will get a an error.(i need to do it with only javaScript.no jquery and stuff like that) this is what i did -
<form>
Write the password here:
<input type="text" id="putPass" name="go2" /> <br />
<input type="button" value="click here" id="press" onclick="pass()" />
</form>
<script type="text/javascript">
var password = ["1234","abcd","0000","1111","4321"]
function pass()
document.getElementById("putPass").value. //it says it has a syntax error and i dont know why...
if (this == password[])
{
document.write("good job!");
}
else
{
alert("try again!");
}
</script>
thank you.
You can try to do that using this code.
http://jsfiddle.net/VAK3N/
<form>
<input type="text" id="putPass" name="go2" />
<br />
<input type="button" value="click here" id="press" />
</form>
<script type="text/javascript">
var password = ["1234", "abcd", "0000", "1111", "4321"];
document.getElementById('press').onclick = function () {
var p = document.getElementById("putPass").value;
if (password.indexOf(p) > -1) {
alert("good job!");
} else {
alert("try again!");
}
}
</script>
Try this
<script type="text/javascript">
var password = ["1234","abcd","0000","1111","4321"];
function pass(){
var userPass = document.getElementById("putPass").value;
if (in_array(userPass, password)){
document.write("good job!");
}
else {
alert("try again!");
}
}
function in_array(needle, haystack){
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}
</script>
var pass = document.getElementById("putPass").value;
var correct = false;
for (var i=0;i<password[].length;i++){
if (password[i] == pass){
correct = true;
break;
}
}
if (correct){
document.write("good job!");
} else {
alert("try again!");
}
Not sure if that exact code will work, but I think that you need to check each password individually in a for loop, you can't compare strings with entire arrays.
I didn't see first that you dont want to use jQuery. So then here is the working code for you.
JS:
var password = ["1234","abcd","0000","1111","4321"]
function pass(){
var input = document.getElementById('putPass').value;
var accepted= false;
for(var pass in password){
if(password[pass] == input ){
accepted= true;
}
}
if(accepted){
alert('good job!');
}else{
alert('try again!');
}
}
HTML:
<form>
<input type="text" id="putPass" name="go2" /> <br />
<input type="button" value="click here" onClick="pass();" id="passSender"/>
</form>