Form validation for textfield not working? - javascript

In javascript, I´m supposed to create a function that checks if a textfield within a form is empty. If it is and the user clicks submit, the user will not be allowed to proceed. I found what I considered a suitable solution to this on w3schools (http://www.w3schools.com/js/js_validation.asp). I´ve checked more times than I can remember and everything seems to be in order, but it´s not working!! Instead, when the submit button is clicked, the website calls a different function I have in javascript which it is not supposed to do...
HTML code
Other code
<p>
<form method="post" name="form" action="" onsubmit="return validateName()">
<label for="fullName">Namn: </label><input id="fullName" class="text" name="namn" type="text"> </input>
</p>
<p>
<label for="epost">Epost: </label><input id="epost" class="text" name="epost" type="email"> </input>
</p>
<p>
<input id="submit" type="submit" value="Skicka"> </input>
</p>
</form>
Other code
Javascript code
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required");
return false;
} else {
return true;
}
}
Clicking the submit button should call this function above (validateName), but instead it calls this function:
function alert() {
return confirm("Do you really wish to leave this website?");
}
I´ve looked through my code multiple times and can´t find anything that seems to be out of place. Can any of you find anything wrong? And maybe suggest a solution that solves my problem so my function will work properly?
I would be very grateful if someone could help me resolve this matter!

alert is a predefined function that you are using correctly once and incorrectly the second time. Simply change the name of YOUR alert function to something else, or just use confirm as it was intended and leave out the function alert part
Correct:
alert("Name required");
Incorrect:
function alert() {
return confirm("Do you really wish to leave this website?");
}
one solution is to do this:
function confirm_leaving(){
return confirm("Do you really wish to leave this website?");
}

That's because you are calling the alert function within your validateName function.
function validateName() {
var a = document.forms["form"]["namn"].value;
if (a == null || a == "") {
alert("Name required"); //<- remove this
return false;
} else {
return true;
}
}

Well i think you may put this code instead of this : function validateName() {
To correct this just put a this command :
function validateName(this) {

Related

JS form validation to ensure that if a name is not entered a pop-up appears

The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".
I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.
The code snippet is attached. The function name in html is called validate();
ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.
function Validate() {
alert(document.getElementsByName("UserInfo")[0].value);
if (name == "" || name == null) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" />
</div>
</fieldset>
You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.
Below is the working model of your snippet.
I had assigned the input value to value and check for existence, do alert if not a valid input.
function Validate(){
const value = document.getElementsByName("UserInfo")[0].value;
if(!value) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<form onsubmit="Validate()">
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" required />
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
UPDATE:
Use required attribute.
Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.
Adding required will abort the submit itself.

How to handle alphanumeric and null in JavaScript?

We are facing an issue on handling null, because if the value is null, it is not reaching the server. Below is the code snippet:
<input ... onchange="return checkEmpty(this);" />
And the JavaScript:
function checkEmpty(value) {
alert("Empty Check() "+value);
if (myTrim(value.length == 0)) {
alert("please Enter Value!"+ value +" value");
return false;
}
return true;
}
We are trying to display one popup for null value and the request should go to the server, but some exception is occurring we are unable to identify it and the request is not coming to server.
You can do this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
While there are ways to solve this specific problem (and the other answer(s) manage to answer that), I'll try to address a more general one.
What you essentially want is the form control to not be empty. Well, you don't need JavaScript for that at all
<input ..... required>
That will prevent the form from submitting unless the required field was filled.
<form>
Try to submit me empty! <input required>
<button>I dare you!</button>
</form>

Javascript form validation, what is missing?

I can't get a form to validate no matter what I try, so I have dumbed it down alot to see if I could get ANYTHING to work, and still when I submit the form the javascript does not validate, and simply sends me to the next page no matter what. You guys see anything wrong??
HTML
<form id="myform" action="/" method="post" onsubmit="return Validate()">
<input id="form_name" type="text" name="name" placeholder="Name" />
<div id="error">Name too short</div>
<input type="submit" id="submit" name="submit" value="Enter" />
JAVASCRIPT IN HEAD
<script language="JavaScript" type="text/javascript">
function Validate() {
if (form.name.value == "") {
$('#error').show();
return false ;
}
return true ;
}
</script>
And in the CSS I have the display for the #error div set to none.
Ultimately I want to check that the user entered at least 4 characters in the text input field, if they didnt then I don't want the form submitted but rather show the error message. But for now I'm just checking to see if its empty to see if I can get anything to work. Any ideas?
First of all remove language from the script tag, it's deprecated.
Then you should not load your script in the head section. Instead put it where body ends to ensure that the HTML has loaded.
Also in your validate function you don't seem to actually target the correct ID's.
Use this:
function Validate() {
if ($('#form_name').val() === '') {
$('#error').show();
return false ;
}
return true ;
}
Replace your javascript for this
function Validate() {
// Use form_name instead of form.name
if (form_name.value == "") {
// This line will break if you do not have jquery.
$('#error').show();
return false ;
}
return true ;
}
Define IDs for tags and use jQuery to get those tags and check their values. For example, if the name tag had id="form_name" you could do something like this:
if ($("#form_name").val() == ""))
$('#error').show();
On the other hand, I recommend you to check jQuery Validate plug-in which is great for validating forms:
http://jqueryvalidation.org/
Instead of
if (form.name.value == "") {
use:
var nameField=document.getElementById("form_name");
if (nameField.value == "") {
Let me know if this works.

Validate forms by function

I have strange problem. I'm trying validate my form by function in JavaScript in this way:
<input type="submit" onclick="return validate();" name="valideButton" value="Something" />
And the validate function:
function validate() {
alert("Some alert!");
var someValidateInputName = document.forms["formName"]["someValidateInputName"].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"]["someValidateInputName"].value);
return false;
}
return true;
}
When I use alert(document.forms["formName"]["someValidateInputName"].value) inside my form there's everything allright, but when I'm calling function validate(); I have an alert with Some alert, but I don't have alert with someValidateInputName. It seems like a function return true when I try to check someValidateInputName and I don't know why...
The script with function is in the same file above the html code.
I validate form on the other my pages in the same way and there was no problem.
alert("Some alert!); should be alert("Some alert!"); the way it is now it tries to alert everything untill the next " meaning it tries to alert half your function.
Ok, I solve the problem.
It was a stupid mistake... and I think that nobody could not help me without more information.
I skip this, because I forget that this can be so important.
My form was closed in foreach loop and many input has name="someValidateInputName", so my outside function doesn't know which input I want to validate. I don't look at the problem in this way, because for me it was strange that function always return true when only I try read the input value.
If somebody forget about this like me, here is the solve:
We need to adding an indexes to name of form and name of input like this:
<input type="submit" onclick="return validate();" name="valideButton <?php echo $j; ?>" value="Something" />
In the same way we have to add index to name of form.
And I send my Index to read the right value via $_POST. I increment $j too.
<input type="hidden" value="<?php echo $j++; ?>" name="Index" />
At the end my validation() look like this:
function validate(index) {
alert("Some alert!");
var someValidateInputName = document.forms["formName"+index]["someValidateInputName"+index].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"+index]["someValidateInputName"+index].value);
return false;
}
return true;
}
If you could place the form out of the foreach you don't be need to an index to form.
Thanks for the trying help!
Cheers

Form Validation using JavaScript and jQuery

I'm making a validation form like so:
<form id="registerform" method="post" onsubmit=return checkformdata();>
<input type="text" name="fname" value=""/>
<input type="text" name="lname" value=""/>
<input type="checkbox" name="privacy" value="1"/>
</form>
checkformdata() Validates only the first name and last name for the checkbox field, which is done using jQuery.
Here is the code that I tried:
jQuery(document).ready(function() {
// Handler for .ready() called.
jQuery('#registerform').submit(function() {
if (!jQuery("#privacy").is(":checked")) {
alert("none checked");
return false;
}
});
});
It is also working but the alert field is comes twice for example firstname is empty then alert for first name and alert for checkbox comes up. I want to show the alert for the checkbox after the checkformdata(); function. Is it possible to give the priority first for javascript then the jquery validation.
Thanks in Advance.
You should only have one functions, which is the second method you are using. Both functions are called now, which is not wat you want. Also, you can use $ instead of jQuery.
Dont use return false! Unless you know what you are doing. Use preventDefault():
$('#registerform').submit(function(event) {
var errorString = [];
// START VALIDATION
if ($("#privacy").is(":checked") ) {
errorString.push("none checked"); // Save for later
}
if ($('[name="fname"]').val).length===0) {
errorString.push("No firstname"); // Save for later
}
if ($('[name="lname"]').val).length===0) {
errorString.push("No lastname"); // Save for later
}
// CHECK IF ERRORS ARE FOUND
if( errorString.length !==0){
event.preventDefault(); // stop the submitting
// Do whatever you like with the string, for example;
alert( "Something went wrong: \n"+errorString.join("\n") ); // alert with newlines
}
// NO ERRORS FOUND, DO SOMETHING
else{
// all good. Do stuff now
}
});

Categories