how to Validate Text boxes before submitting using javascript? - javascript

I have 2 text boxes with default value 0 and a submit button.Before submitting I am calling the following javascript function onSubmit="return(validate_myfrm());".I am not able to validate text_1 with value 0.But for text_2 the default value 0 is validated.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
}
return false;
}
if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
If i return true; after document.myfrm.txt_2.focus(); the page is redirected to next page without confirming the values for txt_2.Pls help

your first condition should be like this
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
}

Use Else If Instaed of if function now it will validate before submission.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
return false;
}
}else if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
}

document.myfrm.txt_bb1.value==0
should be: document.myfrm.txt_1.value==0
also:
Upon setting a return, the function will end and return the false or true set out in your function.
the first if when values are "" or 0 according your condition will always return false. since it is returning false, the function will end and return false.
edit:
here a simple validation example:
<form id="myfrm" name="myfrm" onSubmit="return(validate_myfrm());">
<input type="text" name="txt_1" value="" />
<input type="text" name="txt_2" value="" />
<input type="submit" value="submit" />
</form>
<span id="result"></span>
<script>
function validate_myfrm()
{
if(document.myfrm.txt_1.value!="" && document.myfrm.txt_2.value!="")
{
return true;
} else {
document.getElementById("result").innerHTML="Error fields cannot be empty";
return false;
}
}
</script>
remember in this, that whenever you use return in a function, it will stop the function and return the value set.

Related

Why is my form submitted after cancelling the confirm dialog?

Here is my sample code:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.
Any suggestions?
PS: This code is a demo and different from the real one. But the concept is the same.
You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().
<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
if(con){
return true;
} else {
e.preventDefault();
return false;
}
} else {
return true;
}
}
</script>
You can also return the result of CheckData so the default action will be prevented if it returns false.
<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
return con;
} else {
return true;
}
}
</script>
Change your HTML to this:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation:
The onsubmit event handler is called when the form is submitted.
When the event handler returns false the submission is aborted.

Two fields validation

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" onsubmit="return validate();" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_name();">
<label id="course_name_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<input type="text" id="course_desc" name="course_desc" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:return validate_course_desc();">
<label id="course_desc_info" style="color:rgba(255,255,255,0.6);font-size:13px">
</label>
<button type="submit" name="user_action" value="add" class="btn btn-primary" >Save</button>
<button type="reset" class="btn btn-secondary">Cancel</button>
</form>
<script type="text/javascript">
/**** Specific JS for this page ****/
//Validation things
function validate_course_name(){
var TCode = document.getElementById('course_name').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate_course_desc(){
var TCode = document.getElementById('course_desc').value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
document.getElementById('course_desc_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return true;
}
}
function validate(){
return validate_course_name();
return validate_course_desc();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on two field but the problem is if i give first input field valid input and second invalid form get submitted where am i doing it wrong? ...i am very new to this web so any help will be appreciated:)
UPDATED ANSWER:
Fine! Just to be different =)
One line, should validate both fields regardless if the validate_course_name() returns false.
JSFiddle: http://jsfiddle.net/fVqTY/3/
function validate()
{
return (validate_course_name() * validate_course_desc()) == true;
}
Let false = 0, true = 1. Now do the math :)
function validate(){
var value1 = validate_course_name();
var value2 = validate_course_desc();
if(value1 == true && value2 == true)
return true;
else
return false
}
or You can use
function validate(){
var validate = true;
var TCode = document.getElementById('course_name').value;
var TCode1 = document.getElementById('course_desc').value;
if(! /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
if(! /[^a-zA-Z1-9 _-]/.test( TCode1 ) ) {
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
validate = false;
}
return validate;
}
and then call this function directly
In this function, You should return only once. So what happens here is that when validate_course_name() gets executed, control is already returned to the calling routine. validate_course_desc() line won't execute.
function validate(){
return validate_course_name();
return validate_course_desc();
}
You should do this:
function validate(){
var bol1 = validate_course_name();
var bol2 = validate_course_desc();
if(bol1 == true && bol2 == true)
return true;
else
return false;
}
Your validate method as given below will return as soon as the first validate method (validate_course_name) is called so it will not execute the validate_course_desc method.
function validate(){
return validate_course_name();
return validate_course_desc();
}
The solution is to execute both the validate method and summarise them to create the return value as given in the above answers
change the function validate()
function validate()
{
if(validate_course_name() && validate_course_desc())
{
return true;
}
return false;
}
Once return statement is executed in a function, other statements that are following return statement does not work.
Therefore every time, validate_course_name() function is called , a bool value is returned and the function validate_course_desc() is not even called/executed.
Therefore, the validate function returns true if validate_course_name() is true and false if validate_course_name() return false.Hence , When you give first field valid input and second invalid, form get submitted.
the validation of both inputfields is the same, so you can make one validation function which takes an element-id as parameter:
function validateInputfield(id){
var TCode = document.getElementById(id).value;
if( /[^a-zA-Z1-9 _-]/.test( TCode ) ) {
document.getElementById(id).innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
return true;
}
}
Then you can use the function validate() to check if both inputfields are valid:
function validate() {
if (validateInputfield('course_desc_info') == true &&
validateInputfield('course_name_info') == true) {
return true;
} else {
return false;
}
}

check whether a textarea is empty

Can anyone please tell me what the problem is with this code:
function c(id)
{
var empty = document.getElementById(id);
if(empty.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
This is my html code:
<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>
The value property of the textarea should be checked to determine if it is empty.
var content = document.getElementById(id).value;
if(content.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
Working Example: http://jsfiddle.net/35DFR/2/
Try this:
function c(id)
{
if(document.getElementById(id).value == '')
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
If you want to go a bit further, you might want to trim the value first though.
Update:
From the comments, try changing the 'onchange' to 'onkeyup':
<textarea rows="3" cols="80" id="ta1" onkeyup="c('ta1');"></textarea>
if (YOURFORM.YOURTEXTFIELDVARIABLENAME.value == "")
{
return True
}
function c(id) {
var empty =document.getElementById(id);
if(!empty.value){
window.alert("This field cant be left empty");
return true;
}else{
return false;
}
}
try this

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

JavaScript code returns false, but still the form is submittted

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?
Button code:
<input type="submit" name="button" id="button"
onclick='return formvalidation();' value="Next" />
Non-working function example:
function BlankSite() {
var SiteNum= document.getElementsByName("sitesinput")[0].value;
if ((SiteNum == "") || (SiteNum == 0))
{
alert("You have not selected an amount of sites.")
document.forms[0].button.disabled = true;
return false;
}
}
Function initiator:
function formvalidation()
{
ZeroPhones();
BlankPC();
BlankSite();
BlankSeats();
phone_change();
} // End of formvalidation
This is very strange and I have tried various workarounds all to no avail!
You need to have return false; in the function called by the onclick, in this case formvalidation.
Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.
They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:
function formvalidation(){
{
if (!ZeroPhones())
return false;
if (!BlankPC())
return false;
//
// keep checking for false and return false.
//
// default to return true
return true;
}
So when the functions do in-fact return false, the false return is carried back up through to the bound function.
BlankPC() is called by formvalidation so false is returned into the method formvalidation().
Your formvalidation() is always falling off the end which is the same as returning true.
If you want it to return false when one of your validations fails, it should be:
function formvalidation()
{
retval = true;
retval &= ZeroPhones();
retval &= BlankPC();
retval &= BlankSite();
retval &= BlankSeats();
retval &= phone_change();
return retval;
} // End
This can be optimized a bunch, but you can get the gist of it.
Call the JavaScript function onSubmit of the form instead of calling at button onClick.
JavaScript code
function validate()
{
alert('test');
return false;
}
<form action="test" method="post" onsubmit="return validate();">
This is working fine for me.
formvalidation() isn't returning false.
Maybe you want something like:
function formvalidation()
{
if(!ZeroPhones() ||
!BlankPC() ||
!BlankSite() ||
!BlankSeats() ||
!phone_change())
return false;
}
My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:
function checkPassword() {
// This is my submit button
document.getElementById('nextBtn').setAttribute('disabled', 'disabled');
password1 = document.getElementsByName("pwd1")[0].value;
password2 = document.getElementsByName("pwd2")[0].value;
if (password1 == '') {
// If password not entered
alert ("Please enter Password");
return false;
} else if (password2 == ''){
// If confirmation password not entered
alert ("Please enter confirm password");
return false;
} else if (password1 != password2) {
// If NOT the same, return false.
alert ("\nPassword did not match: Please try again...");
return false;
} else {
document.getElementById('nextBtn').removeAttribute('disabled');
return true;
}
}

Categories

Resources