Form Validation event.preventdefault not working - javascript

I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.
Any help or suggestion will be appreciated
Here is the code
<form id="accmanager" name="accmanager" action="view-acc.php" method="POST">
<h1>Account Management</h1>
<p>
<ul type="none">
<li><input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information</li>
<li><input type="radio" name="optaccmanager" id="addacc" /> Add Account</li>
<li><input type="radio" name="optaccmanager" id="tochangepass" /> Change Password
<ul id="changepass" type="none" style="display: none">
<li><input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" /></li>
<li><input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" /></li>
</ul>
</li>
</ul>
<input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>
and the script code
<script>
//form validation section
$(document).ready(function(){
var changepass = $("#changepass"),
addacc = $("#addacc"),
viewaccinfo = $("#viewaccinfo"),
tochangepass = $("#tochangepass");
addacc.on("click",function(event){
changepass.css("display","none");
$("#submitbtn").attr("value","Add Account");
});
viewaccinfo.on("click",function(event){
changepass.css("display","none");
$("#submitbtn").attr("value","View Account");
});
tochangepass.on("click",function(event){
changepass.css("display","inline");
$("#submitbtn").attr("value","Change Password");
});
$("form").submit(function(event){
var newpassword = $("#newpassword"),
confirmpassword = $("#confirmpassword");
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
});
});

Try to change this:
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
To:
if ((newpassword.val().length == 0) || (confirmpassword.val().length == 0)){
event.preventDefault();
newpassword.attr("title","Please enter new password");
return false;
}

Thanks you all for your help guys I sorted the bug by changing the if block expression.
From previous code:
$("form").submit(function(event){
var newpassword = $("#newpassword"),
confirmpassword = $("#confirmpassword");
if ((newpassword.val == null) || (confirmpassword.val == null)) {
event.preventDefault;
newpassword.attr("title","Please enter new password");
}
});
To new code:
$("form").submit(function(event){
if ($("#tochangepass").is(":checked")){
if ( ($("#newpassword").val().length == 0) || ($("#confirmpassword").val().length == 0) ) {
event.preventDefault();
newpassword.attr("title","Please enter new password");
}
else {
return true;
}
}
}

Related

On submission, this form will not run the validation script

I have tried and tried and cannot figure out why when I submit this form it will not activate the javascript function Validate().
This is nearly an exact replica of another form with namely one change: I've added a textarea and removed some check boxes.
I could really use some help troubleshooting this thing...
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate()">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
function Validate() {
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
There is an exception at the line of code
document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == ""
Dont have any name a7aa41d9-b309-48d7-af97-5a2ce65eb850_First in your document, so that the [0] is undefined.
If you change from
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
to
if (document.getElementsByName('be9953c9-471c-42f4-a1cf-524f5b67fc38_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
The message Please fill out your first name will shown.
You need to prevent the default behavior using e.preventDefault(); otherwise it will try to submit the form
function Validate(e) {
e.preventDefault();
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate(event)">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button type='submit' id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>

onsubmit() form on mobile browser

I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true

Javascript form validating - how do you show validation errors in a single table rather than using alerts

I am new to .asp and Javascript and wondered if someone was able to advise how to show validation errors for fields below the form in a single table or text field rather than using alerts. Alerts and validation are working.
Here is the table that i plan to put the validation errors into:
<asp:Table ID="StatusTable"
runat="server" Width="100%"><asp:TableRow ID="StatusRow" runat="server">
<asp:TableCell ID="StatusTextCell" runat="server" Width="95%">
<asp:TextBox ID="StatusTextBox" runat="server" Width="100%" />
</asp:TableCell><asp:TableCell ID="StatusPadCell" runat="server" Width="5%">
</asp:TableCell></asp:TableRow></asp:Table>
And here is an example of some the Javascript I am using where i need the validation error messages to show in the table rather than from alerts.
Would be extremely grateful for any advise
< script type = "text/javascript"
language = "Javascript" >
function RequiredTextValidate() {
//check all required fields from Completed Table are returned
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
return false;
}
return true;
}
< /script>
function ValidateFields() {
//Validate all Required Fields on Form
if (RequiredTextValidate() && CheckDate(document.getElementById("<%=SickDateTextBox.ClientID%>").value) && CheckTime(this) && ReasonAbsent() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged() == true) {
return true;
}
else
return false;
}
There are many ways that this type of thing can be done, here is one way which I have put together based on what you have so far...
http://jsfiddle.net/c0nh2rke/
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
HTML
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
Script
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
The best JavaScript is no JavaScript.
To that end, consider:
<form action="javascript:alert('Submitted!');" method="post">
<input type="text" name="someinput" placeholder="Type something!" required />
<input type="submit" value="Submit form" />
</form>
Notice how the browser will render native UI to show that the field was left blank? This is by far the best way to do it because it doesn't rely on JavaScript. Not that there's anything wrong with JS, mind, but far too often a single typo in form validation code has caused hours of debugging!

Making JS Alert Look More Professional

Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/

Form submits when "<button>" is clicked

I have an Account Create form. There is no submit button, just a <button>. Right now I have a jQuery validation running when the button is clicked. The validation is being run and the proper errors show up for it, but the form is then submitted and the page reloaded. Even though I have no submit button and not jQuery submit() function anywhere.
HTML:
<form id="accountCreate" method="POST" action="<?=site_url('account/create')?>">
<h3>Create an Account</h3>
<ul>
<li><input type="text" name="email" placeholder="Email..." /></li>
<li><input type="password" name="password" placeholder="Password..." id="password" /></li>
<li><input type="password" placeholder="Verify Password..." id="verifyPassword" /></li>
<li><button id="button">Create</button></li>
</ul>
</form>
JS:
$(document).ready(function() {
$('#button').click(function() {
var password = $('input#password').val();
var passwordV = $('input#passwordVerify').val();
if (password.length >= 6 && password.length <= 24) {
if (password == passwordV) {
} else {
$('div#error').css('display', 'inline');
$('div#error span.errorMessage').text('hey');
}
} else {
alert('yo');
return false;
}
});
});
When no type attribute is defined a <button /> acts as a submit button.
Add type="button" to fix this problem.
<button id="button" type="button">Create</button>
http://www.w3.org/TR/html-markup/button.html#button
You need to specify a default type= attribute for the button, as different browsers can use different defaults. In your case, it looks like the browser has defaulted to type="submit".
$(document).ready(function() {
$('#button').click(function() {
var password = $('input#password').val();
var passwordV = $('input#passwordVerify').val();
if (password.length >= 6 && password.length <= 24) {
if (password == passwordV) {
} else {
$('div#error').css('display', 'inline');
$('div#error span.errorMessage').text('hey');
}
} else {
alert('yo');
return false;
}
//Just add return false
return false;
});
});
You should add evt.preventDefault(); to make the submit only do what you want.

Categories