Javascript check length of (this) in function - javascript

I have a javascript file that validates a form before posting, here's the form...
<form action="#" name="login" method="post" onsubmit="return validate(this);">
<input type="text" name="user"><input type="submit" class="submit">
</form>
Here's the javascript...
function validate(f) {
if (f.user.length < 27 || f.user.length > 34) {
document.getElementById("notice").innerHTML = "Invalid input";
return false;
}
return true;
}
It doesn't seemed to be firing the "notice" message, why can I not detect the length?

I assume you are trying to check the value of whatever is in the input...
Use the value length not the length of the element.
f.user.value.length

Related

Restricting user to leave input field blank using javascript getElementsByClassName method

Created a form. I just want to make form validation. Used javascript to do the job here. Inside jS code created a function named check. In that function if some user leaves the input field blank then the function returns false and in that way I think, can restrict user, but not happening. My question is addressing both getElement..() method and as well as form validation.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname').value;
//checks the inpur field and it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>
The problem is that getElementsByClassName returns an array, so you should use either document.getElementsByClassName('fname')[0].value or document.querySelector('.fname').value (querySelector returns only first found entity)
Here is my complete code after execution.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname')[0].value;
//var fname = document.querySelector('.fname').value;
//checks the input field and if it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>

PHP Form Submits Before Javascript Validation

I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing to submit, but usually my form just ignores codes and submits anyway.
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else {
return true;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
You're making it to complex.
JavaScript:
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else { return true; }
}
HTML:
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
Your validation works fine, but because you are trying to
document.getElementByID("JSError").innerHTML
instead of
document.getElementById("JSError").innerHTML
JS throws an error and never reaches your "return false".
You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).
Example fiddle: http://jsfiddle.net/6tFcw/
1st solution - using input[type=submit]
<!-- HTML -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
// JavaScript
function validateForm(){
var target = document.getElementById("name"); // for instance
if(target.value.length === 0){
alert("Name is required");
return false;
}
// all right; submit the form
return true;
}
2nd solution - using input[type=button]
<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />
// JavaScript
window.onload = function(){
var target = document.getElementById("name");
document.getElementById("submit").onclick = function(){
if(target.value.length === 0){
alert("Name is required");
}else{
// all right; submit the form
form.submit();
}
};
};

Updating form values and stop submitting it

I have an HTML code:
<form action="?" id="form1" method="POST" onsubmit="return g.submitForm();">
<input type="text" name="posX" id="formPosX" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
and JS code:
var g = {
submitForm: function () {
var form = document.forms.form1;
if ( form.posX.value > 100 )
{
form.posX.value = 100;
}
return false;
}
}
and this form is always sending after updating values. My goal is to update wrong values and stop submitting form (I'd like to do it via AJAX). When I remove the IF statement then code works fine, but I need to update some values (and also show an error, if is).
Hope you'll understand my very bad English :)
You're assuming the value in the form input is an integer, when in reality it will be treated as a string data type. Try converting the value to a number before applying the comparison.
if ( parseInt(form.posX.value) > 100 )
{
form.posX.value = "100";
}
I've adapted your code see below (You will need to include the Jquery library):
JS Fiddle
http://jsfiddle.net/boggey79/kN49d/
Form request stopped, because onSubmit return false. You need return true.
Check input value on keypress event:
<script>
function checkPosX(this) {
if ( parseInt(this.value) > 100 ) {
this.value = "100";
}
}
</script>
<form action="?" id="form1" method="POST">
<input type="text" name="posX" id="formPosX" onkeypress="checkPosX(this)" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
Then work fine.

Validate a form using JavaScript

I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<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><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>​​​​​​​​​​​​​​​​​​​
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code

How to run given javascript code given in the following example?

I am trying to run a javascript code but it is not running. I don't know why?
Here is the code sample:
Javascript:
<Script Language="text/Javascript">
function validateForm()
{
var x=document.forms["form1"]["Injection"].value;
var y=document.forms["form1"]["limit"].value;
if (x==null || x=="")
{
alert("Injection must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Limit must be filled out");
return false;
}
return true;
}
</Script>
HTML:
<form name="form1" method="post" action="/OT_Stock/addnewinjection.jsp" onsubmit="return validateForm()">
<input type="text" name="Injection" maxlength="100" size="20" value="" style="textfield">
<input type="text" name="limit" maxlength="100" size="20" value="" style="textfield" >
<input type="submit" value="Add Name" class="buttonmain">
Please tell me where I am going wrong?
Remove the onclick from the button
Add onsubmit="return validateForm()" to the form element.
The crucial bit is the return keyword. Without it the form will always submit. With it, when the validateForm method returns false (invalid form) the form will not submit.
Edit: OP has updated his question with the above suggestions.
forma name is " form1", instead of it should be "form1".Don't use language in the script tag instead use type='text/javascript'.

Categories