I have a subscription form on my website that I am trying to validate. When the user clicks the button signup the function validate() is called and the fields should get validated however im not getting it to work.
Obviously there are some errors in my code. I have tried to fix it with the little knowledge I have, but can't get it to work. I would greatly appreciate it if you could point me into the right directions as to what I am doing wrong.
Code follows:
function validate()
{
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var nat = document.getElementById("nat").value;
var address = document.getElementById("address").value;
var town = document.getElementById("town").value;
var zip = document.getElementById("zip").value;
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var password2= document.getElentById("password2").value;
if (name == "" )
{
window.alert("Please Enter your Full Name")
}
checkNr= isNaN(phone)
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
if (nat == "")
{
window.alert("Please enter your nationality")
}
if (address == "")
{
window.alert("Please Enter your address")
}
if (password != password2)
{
window.alert("Your passwords did not match. Please re-enter")
}
}
</script>
HTML:
<form name="subscribe">
FULLNAME: </strong><input type="text" id="name"/><br />
PHONE NR: <input type="text" id="phone" onblur="validateForm()" /><br />
NATIONALITY:<input type="text" id="nat" /><br />
Address:<input type="text" id="address" /><br />
Town:<input type="text" id="town" /><br />
Zip Code: <input type="text" id="zip" /><br />
Username: <input type="text" id="userName" /><br />
Password:<input type="password" name="password" /><br />
Retype:<input type="password" name="password2" /><br />
<input type="button" value="submit" onclick="validate()" />
</form>
I found these mistakes in your code:
there is no validateForm() function specified in your phone input field
if you want your form to send data, set the type submit, not button on your submit button
if you want to stop the form submitting when something is not filled, hook the onsubmit event of the form:
<form onsubmit="return validate()"> ... // note the return keyword
and the script
function validate() {
...
if(somethingIsWrong) return false; // false stops submitting
else return true; // do submit
}
also note the getElentById typo mentioned by #FranciscoAfonzo
I found my mistake. It looks like you can not use the document.get with a password input field. I took out the password and it worked. It would be great if I could get some input from someone more experience as to why.
A couple of suggestions:
In JavaScript comparisions are done using === (equal to) and !== (not equal to).
If you have only the variable name in the if loop that will also suffice.
Like:
if (address)
{
window.alert("Please enter your address")
}
Related
I have form. Form include name,lastname,email,phone etc. If anybody submit the form without filling email adress my database record this email adress in blank. After this situation if this situation repeat, warning message: same email adress. (First email adress =>blank Second email adress => blank) I want to use regex. Users have to fill email adress. But I could not found any examples. Thanks to much.
Please have a look at the related code:
if (userExists.equals("")) {
bindingResult.rejectValue("email", "error.user", "Lütfen email adresinizi giriniz.");
}
if (userExists != null) {
bindingResult.rejectValue("email", "error.user", "Verilen e-postayla kayıtlı bir kullanıcı var");
}
How about some JavaScript validation code perhaps something like this which doesn't let the form actually submit if the Email field is blank:
<script type="text/javascript"> <!--
function jsValidatePg() {
// Dim var.
var strValid;
// Init.
strValid = "";
// Set var.
if (document.frmMain.Email.value == "") {
strValid = "The Email field must be filled in.";
}
// Determine if valid.
if (strValid == "") {
return true;
}
else {
alert(strValid);
return false;
}
}
//-->
</script>
<form id="frmMain" name="frmMain" action="mypage2.asp" method="post">
<input type="text" name="FirstName" size="15" maxlength="25" value="">
<input type="text" name="LastName" size="15" maxlength="25" value="">
<input type="text" name="Email" size="15" maxlength="25" value="">
<input type="text" name="Phone" size="15" maxlength="25" value="">
<input type="submit" name="btnSubmit" value="Submit" onClick="return jsValidatePg();">
I have written the below code to make a simple form for validation of form inputs through javascript. Here username and passwords are written in the JS code, but it still shows alert message of the else loop even if giving correct credentials on the form.
Please Help?
var user = document.getElementById('username')
var pass = document.getElementById('password')
function user1() {
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" Placeholder="enter username"><br>
<input type="password" name="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
There are a few errors here:
You need to get the values of your inputs
You want to get those values when the button is clicked. Your code is grabbing them only when the page loads. Move the variable assignment into your function
You didn't give the elements ID attributes
function user1() {
var user = document.getElementById('username').value
var pass = document.getElementById('password').value
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" id="username" Placeholder="enter username"><br>
<input type="password" name="password" id="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
Also note that a button's default type is submit which will submit your form and reload the page after the alert is shown when clicked, so you might want to change that to type="button" to prevent that.
I am validating a login form. My password field is working perfectly as I want but while validating USERNAME field I'm calling ajax for username validation i.e to check if username exists and after that if username field is empty calling a js function which shows a message but here I'm having a popup message but I wanted to display that message above the textbox. How can i do that?
Thanks in advance. :)
Add an error holder before the input box.
<span style="display:none;color:#E84344;" id='USERNAME_ERROR'> </span>
<input type="text" name="USERNAME" id="USERNAME" class="form-control input-lg" placeholder="Email or User Name" onchange="CheckLoginCustomer('loginform')"/>
Following Change you need to do in loginvalidation function
function loginvalidation(formname)
{
var form=document[formname];
var USERNAME= form.USERNAME.value;
var PASSWORD= form.PASSWORD.value;
var userNameFlag = form.userNameFlag.value;
if(USERNAME == '')
{
document.getElementById('USERNAME_ERROR').innerHTML = 'Please Enter Registered UserId';
document.getElementById('USERNAME_ERROR').style.display = 'block';
return false;
}
.....
.....
Whereever you dont want to show this error message do the following:
document.getElementById('USERNAME_ERROR').innerHTML = '';
document.getElementById('USERNAME_ERROR').style.display = 'none';
Do the same for others ..
i'm making a code for you please check below link:
https://jsfiddle.net/fatehjagdeo/9way7qc2/1/
or check my code below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form>
<input type="text" id="username"><br>
<input type="password" id="password"><br>
<input type="button" value="submit" id="submit">
</form>
<script>
$(document).on('click','#submit',function(){
$('.error').remove();
var username=$('#username').val();
var password=$('#password').val();
var err=0;
if(username==""){
$('#username').before('<p class="error">Please enter username</p>');
err=1;
}
if(password==""){
$('#password').before('<p class="error">Please enter password</p>');
err=1;
}
if(err==0){
// send your ajax here
}
});
</script>
Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">
For some reason, this code always redirects to education.php regardless of whether or not the fields are blank. I want to verify the fields have values in them, but for some reason they keep redirecting but not writing anything in the database. Any help would be greatly appreciated.
<body>
<form action="education.php" method="post" onsubmit="return validate_fields()">
<div style="text-align: right">
<ul>
First Name: <input id="first_name" name="first_name" size=25/> <br>
Last Name: <input id="last_name" name="last_name" size=25/> <br>
Email: <input id="emailaddress" name="emailaddress" size=25/> <br>
Password: <input id="user_password" name="user_password" type="password" size=25/> <br>
<center><input type="submit" name="submit" id="submit" value="Register Now"/></center>
</ul>
</div>
</form>
<script type="text/javascript">
function validate_fields()
{
var first_name = document.getElementByID("first_name").value;
var last_name = document.getElementById("last_name").value;
alert(""+first_name+" "+last_name);
if (first_name.length < 1 || last_name.length < 1)
{
alert("Please fill in your name.");
return false;
}
var email = document.getElementById("emailaddress").value;
if (email.length < 1)
{
alert("Please fill in your email address.");
return false;
}
var password = document.getElementById("password").value;
if (email.length < 1)
{
alert("Please put in a password.");
return false;
}
alert(first_name+" "+last_name+" "+email);
return false; //was true, changed to see if still redirects.
}
</script>
</body>
You've got a typo on the first line of your function so it isn't returning false (or true), it is just not running at all. This explains both why you don't get any of the alerts and why the form submit goes ahead.
var first_name = document.getElementByID("first_name").value;
// you need a lowercase "d" here ------^
It should be .getElementById(), not .getElementByID().
This is the sort of thing you can easily find for yourself with the appropriate developer tools for your browser. Chrome has this built in (just press ctrl-shift-J to bring up dev tools), or you can add Firebug for FireFox, and IE has had a dev toolbar option for several versions now.
You have a typo here:
var first_name = document.getElementById("first_name").value;
You wrote ByID it sould be ById!