Issue with JS form validation - javascript

I have a simple form, I am trying to use javascript to validate the from but I cant get it to work and I am not sure what I am doing wrong. I am using the same code to validate a form on another project and that works but for some reason the code wont work with another form.
Here is the code
<head>
<script type="text/javascript">
function validate(){
if(document.contactForm.email.value===""){
alert("Please provide a valid email");
document.contactForm.email.focus();
return false;
}
}
</script>
</head>
<form name="contactForm" method="POST" id="contactForm" onsubmit="return(validate()">
<table>
<tr>
<td><input name="name" id="name" class="fields" type="text" placeholder="name"></td>
</tr>
<tr>
<td><input name="email" class="fields" type="email" placeholder="email"></td>
</tr>
<tr>
<td><input name="phone" class="fields" type="phone" placeholder="phone(optional)"></td>
</tr>
<tr>
<td><textarea name="message" class="fieldsMessage" name="message" placeholder="Message"></textarea></td>
</tr>
<tr>
<td><input class="submitButton" type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>

you can use
<input type="email" name="email" required="required" />
html5 will automatic validate it for you.
or you can use this
$("document").ready();
function checkForm(formObj){
$("#table td>span").remove();
var msg="";
for (var i=0; i < formObj.elements.length; i++) {
// check if the form element has a validate attribute.
if (formObj.elements[i].name !=null &&
formObj.elements[i].getAttribute("validate")){
var validationRule =
eval(formObj.elements[i].getAttribute("validate"));
if (!validationRule.test(formObj.elements[i].value)||formObj.elements[i].value==""){
var obj = formObj.elements[i].parentNode;
// add a !!! mark on the validate field
if (obj.nodeName=="TD")
var dialog = formObj.elements[i].getAttribute("validateMsg")+"\n";
msg += dialog;
obj.innerHTML =
obj.innerHTML +"<span style='color:red; font-size:12px;' >"+ dialog +"</span>";
}//--> end test regExp
}//--> end if element has validate attribute
}// end loop through the form elements.
if (msg.length > 0){
return false;
}
else{
return true;
}
}//--> end function
html form:
<form method="post" onsubmit="return checkForm(this);" name="frm">
<table width="430px" id="table">
<tr>
<td>
<input type="text" name="name" validatemsg="please enter your name" validate="/^[a-zA-Z ]*$/" />
</td>
</tr>
<tr>
<td>
<input type="text" name="email" validatemsg="PLease enter email"
validate="/^([\w]+)(.[\w]+)*#([\w]+)(.[\w]{2,3}){1,2}$/" />
</td>
</tr>
<tr>
<td>
<input type="text" name="subject" validatemsg="plaese enter the subject" validate="/^[a-zA-Z1-9 ]*$/" />
</td>
</tr>
</table>
</form>

This line is your main issue...
<form name="contactForm" method="POST" id="contactForm" onsubmit="return(validate()">
should be
<form name="contactForm" method="POST" id="contactForm" onsubmit="return validate();">
Additionally, you may want to set email value to "" like this...
<input name="email" class="fields" type="email" placeholder="email" value="">
because validating email.value==="" might not return true otherwise

Related

Submitting form using Javascript with conditions, have to press submit twice

I have created a form in which I want that if there are some specific entries, the form should not get submitted, and some functions should be executed. But for every other entry, the form should get submitted and work as normal.
function checkuser() {
let name = document.forms[0].name.value;
let email = document.forms[0].email.value;
let message = document.forms[0].message.value;
if ((name == "admin") && (email == "admin#admin.com") && message == ("admin")) {
alert("hey"); //SOME FUNCTION
} else {
document.forms[0].setAttribute("action", "login.php");
document.forms[0].setAttribute("onsubmit", " ");
document.forms[0].submit();
}
}
<form method="post" onsubmit="event.preventDefault(); return checkuser(this)" id="form">
<table align="center">
<tr>
<th><label for="name"> Name : </label></th>
<td> <input type="text" height=100px id="name" name="name" placeholder="Enter your Name..." required> </td>
</tr>
<tr>
<th><label for="email"> Email : </label> </th>
<td><input type="email" id="email" name="email" placeholder="Enter your Email ID..." required></td>
</tr>
<tr>
<th><label for="phone"> Phone Number : </label> </th>
<td><input type="tel" id="phone" name="phone" placeholder="Enter your Phone no..." pattern="[0-9]{10}"></td>
</tr>
<tr>
<th><label for="message"> Message : </label> </th>
<td><textarea id="message" name="message" placeholder="Enter Message..." required></textarea></td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset">
</div>
</form>
It works just fine, but the problem is just that, for normal values, I have to press SUBMIT button twice to redirect the form to "login.php" and submit it. I think, when I press it once, it removes the "submit" method and adds the "action" to the form, and on pressing it twice, it is submitted.
I need it to work with just one click. If I input special values, it should execute the following function, and for normal values, it should directly submit the form using "login.php" as an action.
Any help would be appreciated.
I did it like this...
function checkuser() {
let name = document.forms[0].name.value;
let email = document.forms[0].email.value;
let message = document.forms[0].message.value;
if ((name == "admin") && (email == "admin#admin.com") && message == ("admin")) {
alert("hey"); //SOME FUNCTION
} else {
document.forms[0].submit();
}
}
<form method="post" action="login.php" id="form">
<table align="center">
<tr>
<th><label for="name"> Name : </label></th>
<td> <input type="text" height=100px id="name" name="name" placeholder="Enter your Name..." required> </td>
</tr>
<tr>
<th><label for="email"> Email : </label> </th>
<td><input type="email" id="email" name="email" placeholder="Enter your Email ID..." required></td>
</tr>
<tr>
<th><label for="phone"> Phone Number : </label> </th>
<td><input type="tel" id="phone" name="phone" placeholder="Enter your Phone no..." pattern="[0-9]{10}"></td>
</tr>
<tr>
<th><label for="message"> Message : </label> </th>
<td><textarea id="message" name="message" placeholder="Enter Message..." required></textarea></td>
</tr>
</table>
<div class="buttons">
<input type="button" value="Submit" onclick="checkuser();">
<input type="reset" value="Reset" name="reset">
</div>
</form>

How to create a button that deletes all field when reset button is clicked. The following code performs action instead of resetting the fields

<form id="myForm" action="firstjsp" method="post">
<table>
<tr>
<td> User Name:</td>
<td><input type="text" name="userName"></td></tr>
<tr><td>Email:</td><td><input type="text" name="emailID"></td></tr>
<tr><td>New Password:</td><td> <input type="password" name="userPassword"></td></tr>
<tr><td>Confirm Password: </td><td> <input type="password" name="confirmPassword"></td></tr>
<tr><td>Address: </td><td><input type="text" cols="40" rows="5" name="address"></td></tr>
<tr><td>Gender:</td> <td><input type="radio" name="radioGender" value="Male" >Male</td>
<td><input type="radio" name = "radioGender" value="female">Female </td></tr>
<tr><td><center><input type="submit" value="Submit"></center></td> <td><center><button onClick="myFunction()">Reset</button></center></td></tr>
</table>
</form>
<script>
function myFunction(){
document.getElementByName("myForm").(reset);
}
</script>
<--firstjsp is a servelt file. on clicking reset the program moves to the servlet program instead of displaying the same page-->
This should reset all values in the Form to its defaults. No need for Javascript.
In order to work you need to place the <input ... > inside the same <form> </form> tag as the form you would like to reset.
<input type="reset" value="Reset">
IT is working fine, try this once
<form id="myForm" action="firstjsp" method="post">
<table>
<tr>
<td> User Name:</td>
<td><input type="text" name="userName"></td></tr>
<tr><td>Email:</td><td><input type="text" name="emailID"></td></tr>
<tr><td>New Password:</td><td> <input type="password" name="userPassword"></td></tr>
<tr><td>Confirm Password: </td><td> <input type="password" name="confirmPassword"></td></tr>
<tr><td>Address: </td><td><input type="text" cols="40" rows="5" name="address"></td></tr>
<tr><td>Gender:</td> <td><input type="radio" name="radioGender" value="Male" >Male</td>
<td><input type="radio" name = "radioGender" value="female">Female </td></tr>
<tr><td><center><input type="submit" value="Submit"></center></td> <td><center><input type="Reset" value="Reset" onClick="myFunction()"></button></center></td></tr>
</table>
</form>
<script>
function myFunction(){
document.getElementByName("myForm").(reset);
}
</script>

Trouble submitting my form (with jQuery validation) to the same page with $_POST

I have a form that uses a jQuery system to verify the input. With the default way it works, if there are no errors, it will submit. I am pretty bad with JavaScript, so my question is:
How would I go about making this submit to the same page and put the inputs in the $_POST variable, so it can execute the PHP code to handle the data, while having the jQuery validation working?
What I've noticed:
The type for the submit button must be set to type="button" for the validator to work
Having the type set to button, makes the <form> not submittable
PHP Snippet to validate the input (see if it actually posted into the $_POST variable):
if(isset($_POST)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
echo $username."<br>".$email."<br>".$password;
}
The script for the form:
<form action="" method="post">
<table border=0 id="form" style="padding:10px;">
<tr>
<td>
Username
</td>
<td align=left>
<input name="username" type="text" size="20" jVal="{valid:function (val) { if (val.length < 3) return 'Invalid Name'; else return ''; }}">
</td>
</tr>
<tr>
<td>
Email address
</td>
<td align=left>
<input name="email" type="text" size="40" jVal="{valid:/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/, message:'Invalid Email Address'}" jValKey="{valid:/[a-zA-Z0-9._%+-#]/, cFunc:'alert', cArgs:['Email Address: '+$(this).val()]}">
</td>
</tr>
<tr>
<td>
Password
</td>
<td align=left>
<input name="password" id="password" type="password" jVal="{valid:function (val) { if (val.length < 4) return false; else return true; }, message:'Password of 4 or more characters required'}">
</td>
</tr>
<tr>
<td style="padding-right:20px;">
Verify password
</td>
<td align=left>
<input name="passwordconfirm" id="passwordVerify" type="password" jVal="{valid:function (val) { if ( val != eval('$(\'#password\').val()') ) return false; else return true; }, message:'Password and Verify Password Must Match'}">
</td>
</tr>
<tr>
<td>
<input type="hidden" name="antispam" value="banana" />
<script>
var antiSpam = function() {
if (document.getElementById("antiSpam")) {
a = document.getElementById("antiSpam");
if (isNaN(a.value) == true) {
a.value = 0;
} else {
a.value = parseInt(a.value) + 1;
}
}
setTimeout("antiSpam()", 1000);
}
antiSpam();
</script>
</td>
</tr>
<tr>
<td></td>
<td>
<input id="submitButton" type="button" value="Click here to register!" onClick="if ( $('#form').jVal({style:'blank',padding:8,border:0,wrap:false}) ){ this.form.submit;}">
</td>
</tr>
</table>
</form>
If needed, the files corresponding to the jVal system (validation) can be found here, but they are most likely not needed.
Thanks ahead
PS. Please do not go saying to "narrow down the problem", when I had it narrowed down and posted the specific code snippets, I was told to post the entire code, so here it is.
Use HTML5 validation and <input> types. Your browser can validate e-mail addresses better than you can, for example.
Drop the spam protection; it will prevent actual users from using your page. Use reCAPTCHA.
Don’t use tables for layout. Please? At the very least, use CSS instead of the align attribute.
Don’t assume that everyone’s name is at least three characters long.
<form method="POST">
<table border="0" id="form" style="padding: 10px;">
<tr>
<td>
Username
</td>
<td align="left">
<input name="username" type="text" size="20" required />
</td>
</tr>
<tr>
<td>
Email address
</td>
<td align="left">
<input name="email" type="email" size="40" required />
</td>
</tr>
<tr>
<td>
Password
</td>
<td align="left">
<input name="password" id="password" type="password" required />
</td>
</tr>
<tr>
<td style="padding-right:20px;">
Verify password
</td>
<td align="left">
<input name="passwordconfirm" id="password-confirm" type="password" required />
</td>
</tr>
<tr>
<td></td>
<td>
<button>Click here to register!</button>
</td>
</tr>
</table>
</form>
How would I go about making this submit to the same page and put the
inputs in the $_POST variable, so it can execute the PHP code to
handle the data, while having the jQuery validation working?
You can post to the same page using PHP_SELF. Move the id from your table and add it to your form and use it to submit your form in the javascript code
<form id='form' action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
$('#form').submit() //instead of this.form.submit();
Also, instead of isset($_POST) you should use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}

Validation password not working

I am working on sign up form using html form , but i am facing problem my password cannot validate when I enter wrong password and enter write past does not show anything so what should i do any help.
function validate(){
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
if (pass==pas1)
{
}
else
{
alert("Try again");
}
}
</script>
</head>
<body>
<p class="style2 style8">SIGN UP FORM!!!!</p>
<form onclick="validate()" action="insert.php" method="post">
<table width="270" height="386" border="1" align="right" bordercolor="#993366" bgcolor="#CCCCCC"><td width="260"><table width="232" border="1">
<tr>
<td colspan="2"><span class="style2">loginform</span></td>
</tr>
<tr>
<td width="72"><span class="style5">Name</span></td>
<td width="144"><label>
<input name="name" type="text" id="name" onblur="MM_validateForm('name','','R');return document.MM_returnValue" placeholder="Name" />
</label></td>
</tr>
<tr>
<td width="72"><span class="style5">Gender</span></td>
<td><p>
<label>
<input type="radio" name="gender" value="Male" id="gender"/>
<span class="style5">Male</span></label>
<span class="style5" onfocus="MM_validateForm('fname','','R');return document.MM_returnValue"><br />
<label>
<input type="radio" name="gender" value="female" id="gender" />
female</label>
</span><br />
</p></td>
</tr>
<td width="72"><span class="style5">DOB</span></td>
<td width="144"><span id="sprytextfield1">
<label>
<input name="dob" type="text" id="dob" onblur="MM_validateForm('dob','','R');MM_validateForm('dob','','R');return document.MM_returnValue" placeholder="yyyy/mm/dd"/>
</label>
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span></td>
</tr>
<tr>
<td><span class="style5">Password</span></td>
<td><label>
<input name="pwd" type="password" id="pwd" onchange="MM_validateForm('pwd','','R');return document.MM_returnValue" placeholder="password"/>
</label></td>
</tr>
<tr>
<td width="72"><span class="style5">Confirm Password</span></td>
<td width="144"><label>
<input name="cpwd" type="password" id="cpwd" onchange="MM_validateForm('cpwd','','R');return document.MM_returnValue" placeholder="Confirm Password"/>
</label> </td>
</tr>
<tr>
<td colspan="2"><label>
<div align="center">
<input type="submit" name="submit" id="submit" value="Signup" />
</div>
</label></td>
</tr>
</table>
<label></label></td>
</tr>
</table>
</form>
<h1> </h1>
<script type="text/javascript">
<!--
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "date", {format:"yyyy/mm/dd"});
//-->
</script>
</body>
</html>
there is no pass in your content. You are writing it as:
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
Which should be this:
var pass = (document.getElementById("pwd").value;
var pas1 = (document.getElementById("cpwd").value;
Because the variable's name comes before the = sign. To show that this variable is having this value!
So, now lets use this one and try it like this:
if(pass==pas1) {
// save the password or whatever
} else {
// please try again..
}
This way, the user will check the inputs again. And it they are not working. Then you must first check that whether you are using correct ID of the element, or you are using ClassName as ID!
That's what the issue might be.
Well, for starters,
var = pass(document.getElementById("pwd").value;
var = pas1(document.getElementById("cpwd").value;
should be
var pass = document.getElementById("pwd").value;
var pas1 = document.getElementById("cpwd").value;
Edit:
Also, change onclick="validate()" to onclick="return validate();" and add return false; after the alert("Try again");.
Just small change in your code
function validate(){
var pass = document.getElementById("pwd").value;
var pas1 = document.getElementById("cpwd").value;
if (pass==pas1){
}
else{
alert("Try again");
return false;
}
}

Making validation for both text field and checkbox

Please can I ask for help with my form. I am wanting to make both the text fields and check box required fields. The check box is validating, all I need now is for the text fields to require validation. I'm using javascript.
HTML:
<form name="form" method="post" action="result.php" onSubmit="return checkme()">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Name: </td>
<td> <input name="Name" type="text" id="Name" size="20"></td>
</tr>
<tr>
<td>Email: </td>
<td> <input name="Email" type="text" id="Email" size="20"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> I agree to the terms</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Clear"></td>
</tr>
</table>
</form>
Javascript:
<script language="JavaScript" type="text/JavaScript">
<!--//hide script
function checkme() {
missinginfo = "";
if (!document.form.agree.checked) {
missinginfo += "\n - You must agree to the terms";
}
if (missinginfo != "") {
missinginfo ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo + "\n__________________________________" +
"\nPlease complete and resubmit.";
alert(missinginfo);
return false;
}
else {
return true;
}
}
</script>
Add this JS code for validating the text field
if(document.form.Name.value==""){
missinginfo += "Required field";
}
Same for e-mail field also.
If you convert you doctype to <!DOCTYPE html> then you can use
required="true"
It will be implemented as follow
<input name="Name" type="text" id="Name" size="20" required="true">
Most browsers support HTML5. Alternatively make use of jQuery validation which is fairly simple to use.

Categories

Resources