return value in javascript - javascript

I am new to javascript and I am little bit confused about the syntax.
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
My question is If I write onsubmit="return validateForm()" or write onsubmit="validateForm()". What's the difference between these two syntax. So I submitted before just an example.
Here it is example
Event = function(); or Event = return function();
What's the difference between these two syntax

They're both invalid.
The return statement should be used within a function. The expression following a return statement is what will be returned from the function, so:
function foo() {
return 1234;
}
foo(); // => 1234
If you want to assign a function to the Event identifier, then you would do it like so:
Event = function() {
// function body (what do you want the function to do?)
};

onsubmit="validateForm()" just calls the function and whatever is returned is lost and does not effect anything.
But in onsubmit="return validateForm()" the returned value is returned again and if false will not submit the form and if true will continue the submitting process.
So you can use it like:
function check()
{
if(document.getElementByName("fname").value == ""){
return(false); //Do not submit the form
}
return(true); //Submit the forum
}
<form name="myForm" action="demo_form.asp" onsubmit="return(check());" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Related

calling a method if the validation function is true

When the submit button is pressed, my validation function should check if the fields are validated then call the setProfile method. currently when i click the submit button it will not validate my fields so something must be wrong
<form name="Login" method="post" action="#" onsubmit="return validateForm()">
<input type="text" name="fName" id="name"> <br>
</form>
<input type="submit" name="Update" value="Update">
function validateForm() {
var n = document.forms['Login']['fName'].value;
if(n==null || n=="")
{
alert("Please enter your name");
return false;
}
return true
}
function UpdateProfile() {
document.querySelector('submit').addEventListener('click', e=>{
const myProfile = new Profile
if (e.validateForm === true){
myProfile.setProfile();}
})
}
The most likely reason for your code not working is that your validateForm() function is not getting called at all on submit button press. To find out if that's the case, the simplest thing to do is to add an alert() at the top of the validateForm() function.
If it's indeed not called, google "call javascript function on button click" for a code sample. Here's one: Using an HTML button to call a JavaScript function

Javascript form validation return false error

I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.

getElementById cannot grab control on the form

I have the following search form:
<form method="get" action="SearchResults.asp" id="frmSearch" name="frmSearch">
<input id="q" name="q" type="text" size="50" />
<input type="submit" value="Search" id="button1" name="button1" />
</form>
I add Javascript to the form submit event using the following:
window.onload = function(){
var frm = document.getElementById("frmSearch");
if (window.addEventListener){
frm.addEventListener('submit',function() {validate(frm);} ,false);
}else if (window.attachEvent){
frm.attachEvent('onsubmit', function() {validate(frm);} );
}
}
The validate function is as follows:
function validate(frm) {
alert(frm.id);
var inputs = frm.getElementsByTagName("input");
alert(inputs[0].id);
alert(frm.getElementById("q"));
if (frm.getElementById("q").value=='') {
alert("Please enter your search terms.");
frm.getElementById("q").focus();
return false;
}
frm.getElementById("button1").disabled = true;
return true;
}
The validate function runs but apparently errors out as Javascript ignores the line
frm.getElementById("q")
because alert(frm.id); returns form id "frmSearch", alert(inputs[0].id) returns "q" which is the id of the textbox, but alert(frm.getElementById("q")) does not display anything at all, not even empty alert box.
Can anyone help me diagnose the issue?
getElementById is a method of document, not every HTML element. You'd need to call document.getElementById().

Do some client side validation before posting to server - browser issue

I have a form where I'm posting to PHP server page. Before I POST I do some validation test on the client side, if all good I return true and then submit starts, if there's problems I return false and the submit cancel.
<form onsubmit="return validateForm()" method="post" action="t5.php">
and the validation function :
function validateForm() {
email = document.getElementById('email').value;
name = document.getElementById('name').value;
if ((name==="")|| (email=="") ) {
document.getElementById('validateError').innerHTML="error text";
return false;
}
else
return true;
};
This logic works on last Chrome version, but tried this on Chrome 19 and Firefox and its returns false but still doing immediately a submit.
any ideas?
Instead on calling your validate function on "onsubmit", you can call a similar function on a button click and then if no errors, submit the form via code
Try something like
<form name="testform" id="testform" method="post" action="t5.php">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<input type="button" name="Submit" value="Submit" onclick="validateSubmitForm();"/>
</form>
validateSubmitForm function might have something like this
function validateSubmitForm() {
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
if ((name=="")|| (email=="") ) {
document.getElementById('validateError').innerHTML="error text";
}
else {
document.testform.submit();
}
}
Try using preventDefault() to stop the form from submtting.
and HTMLFormElement.submit() to submit if everything is Ok.
Try this one :
Java script
function validateForm(e) {
email = document.getElementById('email').value;
name = document.getElementById('name').value;
if ((name=="")|| (email=="") ) {
document.getElementById('validateError').innerHTML="error text";
e.preventDefault();
}
};
HTML
<form onsubmit="validateForm(event)" method="post" action="t5.php">

validation not working for js

<html>
<head>
</head>
<body>
<form class="form-horizontal cmxform" id="validateForm" method="get" action="../../course_controller" autocomplete="off">
<input type="text" id="course_name" name="course_name" placeholder="Enter Course Name..." class="row-fluid" required onkeyup="javaScript:validate_course_name();">
<label id="course_name_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" onClick="javaScript:validate();" >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 ) ) {
course_name_info.innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
return false;
}
else
{
course_name_info.innerHTML=" ";
return true;
}
}
function validate(){
validate_course_name();
}
</script>
</body>
</html>
So this the code ...I am applying alpha numeric validation on one field but even if i give invalid input like some other characters the form is getting submitted where am i doing it wrong?
i am very new to this web so any help will be appreciated:)
There are several issues here. First, you are never returning the result, so even if the function results in false, it is not returned to the form so the form goes on its merry way. To fix, you can add an onsubmit to the form tag, or even better attach an onsubmit event to the form.
onsubmit="return validate();"
Second, you only need the one function, calling a function from another function is not necessary here, and results in an additional level of difficulty since you will need to return the result to the wrapper function, which will then need to return that result to the form.
//Validation things
function validate() {
var TCode = document.getElementById('course_name').value;
if (/[^a-zA-Z1-9 _-]/.test(TCode)) {
course_name_info.innerHTML = "Please Enter Only Alphanumeric or _,-,' ' ";
return false;
} else {
course_name_info.innerHTML = " ";
return true;
}
}
Here is a working fiddle of your example: http://jsfiddle.net/duffmaster33/nCKhH/
Your validate() function should return the result of the validation. Currently the result of validate_course_name is discarded. In other words, it should look something like this
function validate(){
return validate_course_name();
}
Also you might want to move the validation to
<form onsubmit="return validate()" ...
You need to wrap course_name_info with a getElementById
document.getElementById('course_name_info').innerHTML="Please Enter Only Alphanumeric or _,-,' ' ";
and then change the style of the label so the font isn't white on white background.
Hope that fixes it.

Categories