Validate form fields with javascript - javascript

folks.
I hope you don't see this as a silly question because i am new to JavaScript. I did my research on how to solve this problem but the answers i found on stack overflow were kind of too high for me right now. And i don't like to copy codes either. I want to learn it. My JavaScript code worked on one field but didn't work for all fields even when i did a loop.
Please you are free to show me how to do this professionally. I would be grateful to see many approaches or methods. Gracias
function Validate(x){
var required = document.getElementsByClassName("required");
for(var x = 0; x > required.length; x++){
if ((required[x].value == "") || (required[x].value == null)) {
required[x].style.backgroundColor = "red";
required[x].style.color = "white";
} else {
required[x].style.backgroundColor = "";
required[x].style.color = "#777";
}
}
}
<form id="form1" name="form1" method="post" action="">
<p>
<label for="textfield">Name</label><br />
<input type="text" name="name" id="name" class="forme required" onblur="Validate(name)" />
<br />
<label for="textfield">Surname</label><br />
<input type="text" name="surname" id="surname" class="forme required" />
<br />
<label for="textfield"> School</label><br />
<input type="text" name="school" id="school" class="forme required" />
<br />
<label for="textfield">Mobile</label><br />
<input type="text" name="mobile" id="mobile" class="forme required" />
<br />
<label for="email"> Email</label><br />
<input type="text" name="email" id="email" class="forme required"/>
</p>
<p>
<input type="reset" name="reset" id="reset" value="Reset" />
<input type="submit" onclick="Validate()" name="submit" id="submit" value="Submit" />
</p>
</form>
Be grateful for ya time.

as mentioned in the comments of your question, you used the wrong sign (">" ist false, "<" is true). But your code has some more failures.
The for attribute on the label elements should always point to the respective input field, so use the ID of the input field.
It's may better to use the JavaScript addEventListener method instead of the DHTML attribute onclick, but that is probably a matter of taste.
document.getElementById("submit").addEventListener("click", function(event){
var req = document.querySelectorAll("form input.required"),
error = false;
for(var i = 0; i < req.length; i++){
if(req[i].value.trim() == ""){
if(!error){
error = true;
}
req[i].style.setProperty("color", "#ffffff");
req[i].style.setProperty("background-color", "#ff0000");
} else {
req[i].style.removeProperty("color");
req[i].style.removeProperty("background-color");
}
}
if(error){
// Prevent Form Submit
event.preventDefault();
}
});
<form id="form1" name="form1" method="post" action="">
<p>
<label for="name">Name</label><br />
<input type="text" id="name" name="name" class="forme required" />
</p>
<p>
<label for="surname">Surame</label><br />
<input type="text" id="surname" name="surname" class="forme required" />
</p>
<p>
<label for="school"> School</label><br />
<input type="text" id="school" name="school" class="forme required" />
</p>
<p>
<label for="mobile">Mobile</label><br />
<input type="tel" id="mobile" name="mobile" class="forme required" />
</p>
<p>
<label for="email"> Email</label><br />
<input type="email" id="email" name="email" class="forme required" />
</p>
<p>
<input type="reset" id="reset" name="reset" value="Reset" />
<input type="submit" id="submit" name="submit" value="Submit" />
</p>
</form>
Please note: Don't use ONLY JavaScript to validate your form fields. You should always check the passed user informations on the server side too, because you can't control the user.
Have fun learning JavaScript.
Sincerely,
Sam.

Related

Trying To Match Two Fields Before Form Submit With Javascript

I am trying to match two fields with the result in my javascript before the form gets submitted but not working.
I don't want the form to get submitted if the results don't match.
Please what is the solution? Thanks.
Code Below;
function Check(){
var done=0;
var check=document.check.phone.value;
var check=document.check.pcode.value;
if (phone=="08023" && pcode=="12345") {
alert ("Result Match!");
done=1;
return fasle;
}
if (done==0) {
alert("Result Don't Match!");
}
}
<form action=" " method="post">
<input name="phone" maxlength="11" type='tel' id="phone" placeholder="0000-000-0000" required="" />
<br/><br/>
<input name="pcode" maxlength="11" type='tel' id="pcode" placeholder="0000-000-0000" required="" />
<br/><br/>
<button class="button" onClick="javascript:Check()" name="Submit" type="submit" value="Login"><span>Log In </span></button>
</form>
You have several mistakes in your code, I have cleaned it up a bit for you.
function Check() {
var done = 0;
var phone = document.check.phone.value;
var pcode = document.check.pcode.value;
if (phone=="08023" && pcode=="12345") {
alert("Result Match!");
done = 1;
} else {
alert("Result Don't Match!");
}
}
<form name="check" action=" " method="post">
<input name="phone" maxlength="11" type='tel' id="phone" placeholder="0000-000-0000" required="" />
<br /><br />
<input name="pcode" maxlength="11" type='tel' id="pcode" placeholder="0000-000-0000" required="" />
<br /><br />
<button class="button" onClick="javascript:Check()" name="Submit" type="submit" value="Login">
<span>LogIn</span></button>
</form>

Check whether password and re-entered password are same or not in Javascript

I have a html signup form in which I want to check whether password and re-entered password are same or not in Javascript.
Here is the code :
< script >
function pass() {
var pas = document.getElementById("pass");
var rpas = document.getElementById("rpass");
if (pas.value != rpas.value) {
document.getElementById("error").innerHTML = "Enter same password in Retype Password..";
} else {
document.getElementById("error").innerHTML = "";
}
}
<
/script>
<form action="">
<div id="signup" class="tab-content show">
<input type="text" placeholder="Name" name="name" id="name" />
<br />
<br />
<input type="password" placeholder="Password" name="pass" id="pass" />
<br />
<br />
<input type="password" placeholder="ReType Password" name="rpass" id="rpass" />
<br />
<br />
<input type="email" placeholder="Email" name="email" id="email" />
<br />
<br />
<input type="radio" value="Male" name="gender" id="gender" checked="checked" />Male
<input type="radio" value="FeMale" name="gender" id="gender" />Female
<br />
<br />
<input type="submit" value="Submit" name="submit" id="submit" onclick="pass()" />
<p id="error"></p>
</div>
</form>
Problem is that Javascript is not working..
The problem is that you are submitting the form there. You have used onClick event on submit button, but when submit button is pressed form is submitted and you can call a function in the form tag in onSubmit attribute and then you have to stop form submission otherwise the form will be submitted and the page will reload
You need to change input type "submit" to input type="button".
<script >
function pass(){
var pas = document.getElementById("pass");
var rpas = document.getElementById("rpass");
if (pas.value != rpas.value){
document.getElementById("error").innerHTML="Enter same password in Retype Password..";
}
else{
document.getElementById("error").innerHTML="";
}
}
</script>
<form action="">
<div id="signup" class="tab-content show">
<input type="text" placeholder="Name" name="name" id="name" />
<br />
<br />
<input type="password" placeholder="Password" name="pass" id="pass" />
<br />
<br />
<input type="password" placeholder="ReType Password" name="rpass" id="rpass" />
<br />
<br />
<input type="email" placeholder="Email" name="email" id="email" />
<br />
<br />
<input type="radio" value="Male" name="gender" id="gender" checked="checked"/>Male
<input type="radio" value="FeMale" name="gender" id="gender" />Female
<br />
<br />
<input type="button" value="Submit" name="submit" id="submit" onclick="pass()" />
<p id="error"></p>
</div>
</form>
You can check below code on W3schools
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form action="">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
Password:<br>
<input type="password" name="password" id="pswd">
<br><br>
Re-Password:<br>
<input type="password" name="password" id="rpswd">
<br><br>
<input type="button" value="Submit" onclick="pass()">
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>
<script>
function pass() {
var paswd = document.getElementById("pswd").value;
var rpswd = document.getElementById("rpswd").value;
alert(paswd !== rpswd);
}
</script>
</body>
</html>
Also you can follow the answer of whis san

HTML form with custom function call

I am developing Universal windows 8.1 app and I have a page for creating new contact.
In purpose to validate input fields I put them in form. My form action not supposed to go to service it just need to validate fields and call custom function.
HTML:
<form name="myform" onSubmit="JavaScript:OnSubmitForm()">
<div>
<label>
First name<br />
<input id="contactFirstName" class="win-textbox" type="text" name="firstName" required />
</label>
</div>
<div>
<label>
Last name<br />
<input id="contactLastName" class="win-textbox" type="text" name="lastName" />
</label>
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/>
</form>
JavaScript:
document.addEventListener('DOMContentLoaded', function() {
function OnSubmitForm()
{
alert('click');
}
});
My alert is never calls in plain HTML project neither in WinJS app. I also tried with:
<form name="myform" onsubmit="return OnSubmitForm();">
and the same.
Does it a good approach at all, to use form just for input fields validation or there is better way, and why this does not work ?
Inline event-binding expects functions to be under global-scope and that is one of the reason one should not use it!
In your example, OnSubmitForm is under the local scope of DOMContentLoaded handler. Best approach would be to use addEventListener and with the current code, place OnSubmitForm out of DOMContentLoaded.
document.getElementById('myform').addEventListener('submit', function(e) {
e.preventDefault(); //to prevent form submission
alert('click');
});
<form name="myform" id='myform'>
<div>
<label>
First name
<br />
<input id="contactFirstName" class="win-textbox" type="text" name="firstName" required />
</label>
</div>
<div>
<label>
Last name
<br />
<input id="contactLastName" class="win-textbox" type="text" name="lastName" />
</label>
</div>
<input type="submit" value="Submit" />
<input type="button" value="Cancel" />
</form>
With current approach:
function OnSubmitForm() {
alert('click');
}
<form name="myform" onSubmit="JavaScript:OnSubmitForm()">
<div>
<label>
First name
<br />
<input id="contactFirstName" class="win-textbox" type="text" name="firstName" required />
</label>
</div>
<div>
<label>
Last name
<br />
<input id="contactLastName" class="win-textbox" type="text" name="lastName" />
</label>
</div>
<input type="submit" value="Submit" />
<input type="button" value="Cancel" />
</form>
Have you tried parsley.js?
I created this fiddle to show you a quick example.
<form name="myform">
<div>
<label>
First name<br />
<input id="contactFirstName" data-parsley-required-message="First name required" class="win-textbox" type="text" name="firstName" required data-parsley-trigger="change focusout" data-parsley-pattern="/^[a-zA-Z]*$/"/>
</label>
</div>
<div>
<label>
Last name<br />
<input id="contactLastName" class="win-textbox" type="text" name="lastName" />
</label>
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/>
<script src="http://parsleyjs.org/dist/parsley.js"></script>
<script>
window.ParsleyConfig = {
errorsWrapper: '<div></div>',
errorTemplate: '<div class="alert alert-danger parsley" role="alert"></div>',
errorClass: 'has-error',
successClass: 'has-success'
};
</script>

How to stop php to execute after getting a false as return in js

I have a validator for phone no with js and it is working fine but eve after getting false as return the php code gets executed. how to stop it from executing.
This is my js function
function phonenumber(inputtxt){
var phoneno = /^\d{10}$/;
if(inputtxt.value.match(phoneno))
{return true;}
else
{alert("message");
return false;}
}
This is my html code
<form action="get_quote.php" method="post" name="quote" class="quote">
<font class="label"><input type="text" class="quote" placeholder="Enter Your Name" autocomplete="off" name="name" required/>
<input type="text" class="quote" autocomplete="off" placeholder="Enter Your Mobile Number" name="mobile" required/>
<input type="email" class="quote" autocomplete="off" placeholder="Enter Your Email Id" name="email" required/><br />
</center>
<div>
<div class="rest">
<input type="radio" id="new" name="condition" class="rest" checked>New<br />
<input type="radio" id="mod" name="condition" class="rest"/>Modification
</div>
<div class="rest">
<input type="checkbox" name="web" />Website<br />
<input type="checkbox" name="android" />Android Application<br />
<input type="checkbox" name="ios" />IOS Aplication<br />
<input type="checkbox" name="seo" />SEO/SMO<br />
<input type="checkbox" name="desktop" />Computer Software<br />
</div>
</div>
<br><center>
<textarea name="desc" placeholder="Enter Your Description" required></textarea><br /></font>
<button type="submit" onclick="phonenumber(document.quote.mobile)" class="quote">Get Quote</button>
</form>
Working Fiddle.
Add return in onclick before function call :
<button type="submit" onclick="return phonenumber(document.quote.mobile)" class="quote">Get Quote</button>
Hope this helps.
You can get mobile field value by using this:
function phonenumber()
{
var inputtxt = document.getElementsbyName("mobile");
var phoneno = /^\d{10}$/;
if(inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
And than no need to pass param in onclick event, use this:
<button type="submit" onclick="phonenumber()" class="quote">Get Quote</button>

Password validation (2 Textboxes, comparision)

before you blame me, yes I was looking for something similar for about a hour, but sadly I couldn't find my error, atleast the Questions I was looking for in stackoverflow didn't gave me a correct answere, as I have almost exactly the same thing (not Copy and Paste).
However could someone explain me, why my code (javascript) isn't working?
I am playing around with it for some hours now but I can't find it.
<html>
<head>
<title>Anmeldung/Login</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script>
function abc(){
var a = document.getElementById('pw').value;
var b = document.getElementById('repw').value;
if(a==b){
alert(yes)
}
}
</script>
</head>
<body>
<div id="banner">
<p>NAME/ÜBERSCHRIFT</p>
</div>
<form id="loginpanel">
<fieldset>
<legend>LOGIN</legend>
<p class="textinput">Benutzername: <input name="id" type="text" size="30" maxlength="30"></p>
<p class="textinput">Passwort: <input name="pw" type="password" size="30" maxlength="15"></p>
<input class="button" type="button" name="login" value="Anmelden"/>
</fieldset>
</form>
<p id="option"> ...oder Registrieren!</p>
<form id="registerpanel">
<fieldset>
<legend>REGISTER</legend>
<p class="textinput">Benutzername: <input name="id" type="text" size="30" maxlength="30"></p>
<p class="textinput">eMail: <input name="email" type="text" size="30" maxlength="30"></p>
<p class="textinput">Passwort: <input name="pw" type="password" size="30" maxlength="30"></p>
<p class="textinput">Passwort wiederholen: <input name="repw" type="password" size="30" maxlength="30"></p>
<input class="button" type="button" onclick="abc()" name="register" value="Registrieren"/>
</fieldset>
</form>
</body>
I would be happy if someone can give me an answere!
Thank you for taking your time :)!
You must have inputs with id attribute with values pw+repw. Having only a name attribute will not work
example: <input name="repw" id="repw" type="password" size="30" maxlength="30">
Corrected version (only relevant parts):
<script>
window.abc = function(){
var a = document.getElementById('pw').value;
var b = document.getElementById('repw').value;
if(a==b){
alert("yes")
}
}
</script>
...
<form id="registerpanel">
<fieldset>
<legend>REGISTER</legend>
<p class="textinput">Benutzername: <input name="id" type="text" size="30" maxlength="30"></p>
<p class="textinput">eMail: <input name="email" type="text" size="30" maxlength="30"></p>
<p class="textinput">Passwort: <input name="pw" id="register-pw" type="password" size="30" maxlength="30"></p>
<p class="textinput">Passwort wiederholen: <input name="repw" id="register-repw" type="password" size="30" maxlength="30"></p>
<input class="button" type="button" onclick="abc()" name="register" value="Registrieren"/>
</fieldset>
</form>
Note the added IDs. I didn't do pw and repw because having plain pw in login made more sense to me (11684) (don't forget to add that in the login form). Because I'd do register-pw I went for consistency and did register-repw. But it doesn't matter what these IDs are as long as they are unique.
And I changed the typo alert(yes) into alert("yes") because obviously the first throws a reference error.
A working JSFiddle: http://jsfiddle.net/7NZUc/

Categories

Resources