I am having some trouble having my password validation working, I think that the javascript is now correctly defined but I am not able to validate the form successfull as it keeps posting regardless of the errors.
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model Models.ResetModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#close').click(function (event) {
closeAjax();
event.cancelBubble = true;
event.returnValue = false;
event.preventDefault();
event.stopPropagation();
});
});
$(document).ready(function () {
$("#resetForm").validate({
rules: {
password: {
require: true,
minlength: 6
},
confirmpassword: {
require: true,
minlength: 6,
equalTo: "#password"
}
},
messages: {
password: {
require: "You must enter a password!",
minlength: "Password must contain at least 6 characters"
},
confirmpassword: {
require: "You must enter a password confirmation!",
minlength: "Password must contain at least 6 characters",
equalTo: "Password and Password Confirmation fields do not match!"
}
}
});
});
here is the HTML:
<div class="form_container">
<div class="logo">
<img class="logo" src="#Url.Content("~/Content/SP_Logo_white.png")" alt="SmartPlant Cloud"/>
</div>
<div class="reset">
<h3>Password Reset</h3>
<div class="reset-help">
<p>Forgot your password? Use the form to change or reset your password.</p>
</div>
#using (Html.BeginForm("Reset", "Reset", new { qString = Model.QueryString, #id = "resetForm" } ))
{
<label for="reset">UserName:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">New Password:</label>
<input type="password" id="password" name="password" /><br />
<label for="confirmpassword">Confirm Password:</label>
<input type="password" id="confirmpassword" name="confirmpassword" />
<p><input type="submit" id="submit" value="Submit" /></p>
}
</div>
You need to create the function to validate the form client side that will return a value "false" value if the data entered is incorrect, hence the from will not be submitted. This does NOT involve PHP it's to catch it before the PHP is loaded..
You can do validation checks also- server side as well.
function Validate()
{
//insert javascript validation check
return false;
}
<form onsubmit="return Validate();" action="your.php" method="post" name="your name" >
<label for="reset">UserName:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">New Password:</label>
<input type="password" id="password" name="password" /><br />
<label for="confirmpassword">Confirm Password:</label>
<input type="password" id="confirmpassword" name="confirmpassword" />
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
Hope this helps.
Related
Is there away to validate a form in js and if its valid execute a js function?
basiclly it should check if the form is valid then open the default email program with some entries
like so ->
Yes you can
$('#loginform').validate({
rules: {
email: {
required: true,
email: true,
maxlength: 30
},
password: {
required: true,
minlength: 8,
maxlength: 20,
}
},
submitHandler: function(form) { // for demo
return false; // for demo
}
});
$("#submit").click(function() {
if ($('#loginform').valid()) {
alert("Open mail program");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js" integrity="sha256-+BEKmIvQ6IsL8sHcvidtDrNOdZO3C9LtFPtF2H0dOHI=" crossorigin="anonymous"></script>
<form id="loginform">
<div class="form-group">
<input class="form-control form-control-lg" id="email"
name="email" type="text" placeholder="Email" autocomplete="off">
</div>
<div class="form-group">
<input class="form-control form-control-lg" id="password" name="password"
type="password" placeholder="Password">
</div>
<button type="button" id="submit" class="btn btn-primary btn-lg btn-block">Login </button>
</form>
I have written a validation code for my form in jQuery. Everything seems to be correct, but it doesn't work. Help me!
HTML FORM:
<form role="form" name="form1" id="form1">
<div class="form-group">
<label for="usr">Contact Name</label>
<input type="text" name="usr" class="form-control" id="usr" placeholder="Full Name">
</div>
<div class="form-group">
<label for="pwd">Company Name</label>
<input type="text" class="form-control" id="pwd" placeholder="Company Name">
</div>
<div class="form-group">
<label for="eml">Email</label>
<input type="email" class="form-control" id="eml" placeholder="Email">
</div>
<div class="form-group">
<label for="phn">Contact Number</label>
<input type="number" class="form-control" id="phn" placeholder="98689-98689">
</div>
<div class="form-group">
<label for="comment">Remarks</label>
<textarea class="form-control" rows="3" id="comment"></textarea>
</div>
<button id="submtbtn" style="height:30px ; width:60px; padding: 5px 5px;" type="button" class="btn btn-info" onClick="AddNew(); this.form.reset()">Insert</button>
<button style="height:30px ; width:60px; padding: 5px 5px;" type="button" class="btn btn-info" onClick="this.form.reset()">Clear</button>
<button id="cnclbtn" style="height:30px ; width:60px; padding: 5px 5px; background-color: #f1f1f1; " type="button" class="btn btn-default">Cancel</button>
</form>
Here is the validation script:
$(document).ready(function () {
$("#form1").validate({
rules: {
usr: "required",
pwd: "required",
eml: {
required: true,
email: true
},
phn: {
required: true,
minlength: 10
}
},
messages: {
usr: "Please enter your first name",
pwd: "Please enter your last name",
eml: {
required: "Please provide Email address ",
email: "Please enter valid Email address"
},
phn: {
required: "Please provide a Phone Number",
minlength: "Your Phone Number must be 10 digits"
}
}
});
$("#submtbtn").click(function () {
$("#form1").valid();
});
});
Please point out the error. Thank you.
JSFiddle https://jsfiddle.net/cherry1993/vwo0r0h6/
In your jsFiddle, after removing the <script> and </script> tags from the JavaScript pane, and including jQuery and the jQuery Validate plugin, it started working... but only for the usr field.
https://jsfiddle.net/vwo0r0h6/2/
It does not work on any of the other fields because you forgot to include a name attribute on those input elements. This plugin only uses the name attribute, not the id, to keep track of the form inputs.
<input type="text" class="form-control" name="pwd" placeholder="Company Name">
Working DEMO: https://jsfiddle.net/vwo0r0h6/3/
Bonus:
You don't need to worry wether the value within your custom message matches the rule's parameter. Simply use the parameter's placeholder, {0}, within the custom message and its value will get entered dynamically. See working demo above.
minlength: "Your Phone Number must be {0} digits"
This question already has an answer here:
Interaction between JQuery validation and form submit handler: Broken, or am I doing something wrong?
(1 answer)
Closed 8 years ago.
So I've got a form with onsubmit="SubmitForm()" and also a $().validate(). The problem is that when submit is clicked, the .validate() works, but SubmitForm() also runs. I'm a little confused, could someone help me out?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#eclub').validate({ // initialize the plugin
rules: {
FirstName: {
required: true,
minlength: 2,
},
LastName: {
required: true,
minlength: 2
},
'Email Address': {
required: true,
email: true
},
Zip: {
required: true,
minlength: 2
},
DOB_Month: {
required: true,
minlength: 2,
},
DOB_Day: {
required: true,
minlength: 1
},
over18: {
required: true
}
}
});
});
function autoDMA() {
var zip_code = $('#zip_code').val();
$.ajax({
url: 'get_zipCode.php',
type: 'POST',
data: {zip_code:zip_code},
success:function(data){$('#dma_code').val(data);}
});
}
function SubmitForm()
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
</script>
<div id="" style="width:60%;">
<br/>
<!-- <form action="http://cl.exct.net/subscribe.aspx" id="eclub" method="post" onsubmit="return validateForm(this)" style="width:100%;"> -->
<form method="post" id="eclub" onsubmit="SubmitForm()">
<input name="thx" value="http://papamurphys.com/Deals/ThankYou" type="hidden">
<input name="dma" value="" type="hidden" id='dma-set' />
<input name="dma2" value="" type="hidden" />
<input name="MID" value="29115" type="hidden" />
<input name="lid" value="846154" type="hidden" />
<input name="lid" value="17516793" type="hidden" />
<input name="SubAction" value="sub_add_update" type="hidden" />
<input type="hidden" name="status" value="normal" />
<input name="Birthdate" value="" type="hidden" id="bday"/>
<div class="clearfix">
<label for="name"><span class="bold">First Name</span></label><br />
<input class="required" name="FirstName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="name"><span class="bold">Last Name</span></label><br />
<input class="required" name="LastName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Email</span></label><br />
<input class="required" name="Email Address" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Mobile Number</span></label><br />
<input class="required" name="MobileNumber" type="text" placeholder="" />
</div>
<div class="clearfix">
<span class="bold">Zip/Postal Code</span><br />
<input class="required zip" id="zip_code" name="PostalCode" type="text" onkeyup="autoDMA()" placeholder="" maxlength="5" size="5" />
</div>
<div class="clearfix">
<input class="zip" id="dma_code" name="DMACode" type="text" placeholder="" maxlength="5" size="5" style="display:none;" />
</div>
<div class="clearfix">
<span class="bold">Birthday</span><br />
<input class="month user required" name="DOB_Month" type="text" placeholder="MM" maxlength="2" style="width:48px;" />
<input class="day user required" name="DOB_Day" type="text" placeholder="DD" maxlength="2" style="width:48px;" />
</div>
<div class="clearfix">
<input class="age user" class="required" name="emailDeals" id="emailDeals" type="checkbox"/> Sign me up for email deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="mobileDeals" id="mobileDeals" type="checkbox"/> Sign me up for mobile deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="over18" id="over18" type="checkbox"/> I'm over 18
</div>
<input class="join-btn" type="submit" style="float:right;line-height:14px;cursor: pointer" onclick="pageTracker._trackPageview('Forms', 'Submit', 'eClubSignUp')" value="SUBMIT" />
<!--<input type="button" class="join-btn" value="" onclick="validateForm()" />-->
</form>
</div>
Why don't you use submitHandler callback in validate()?
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
Anything you want to do when the form is valid, and you click the button, would be done inside the plugin's submitHandler option. (Not via an external function triggered by an inline handler)
$('#eclub').validate({
// rules and other options,
submitHandler: function (form) {
if ($("#emailDeals").is(':checked')) {
document.forms['eclub'].action = 'http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target = '_blank';
form.submit(); // submit the form // this is the default
}
if ($("#mobileDeals").is(':checked')) {
document.forms['eclub'].action = '/assets/waterfall/waterfall_rest.php';
form.submit(); // submit the form // this is the default
}
}
});
Working DEMO: http://jsfiddle.net/vbs32y9u/
As #Mike says Why you use SubmitForm()?
Anyway you can try this:
function SubmitForm()
{
if ($("#eclub").valid())
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
else
{
return false;
}
}
below is example of form validation using jquery what I copied from internet,
however, when I used <g:form> instead of <form> validate function not work.
Please suggest better way to validate form using groovy form
Thanks
<html>
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<link href="runnable.css" rel="stylesheet" />
<!-- Load jQuery and the validate plugin -->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<!-- jQuery Form Validation code -->
<script>
// When the browser is ready...
$(function() {
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<!-- The form that will be parsed by jQuery before submit -->
<form action="" method="post" id="register-form" novalidate="novalidate">
<div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>
</body>
</html
Your <form> tag contains novalidate Attribute which Indicates that the form is not to be validated on submit, get rid of that first. Following is sample code from test project to use jquery validation with <g:form>. Sorry for long code.
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="esn-registration">
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("emailId", function(value, element) {
return this.optional(element) || /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value);
}, "Email is invalid: Enter a valid email");
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-z][\w.-]{3,20}$/i.test(value);
}, "Characters, numbers, ( _ ), ( - ) and ( . ) only");
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstName: "required",
lastName: "required",
emailId: {
required: true,
email: true,
emailId: true
},
username: {
required: true,
minlength: 3,
maxlength: 20,
username: true
},
password: {
required: true,
minlength: 6
}
},
messages: {
firstName: { required: "Please enter your first name" },
lastName: { required: "Please enter your last name" },
emailId: {
required: "Please enter an email address",
email: "Please enter a valid email address"
},
username: {
required: "Please enter an username",
minlength: "Username must exceed 3 characters",
maxlength: "Username cannot exceed 20 characters"
},
password: {
required: "Please provide a password",
minlength: "Password must exceed 6 characters"
}
},
submitHandler: function(form) {
if(signupForm.valid()){
form.submit();
$('button[type="submit"]').removeAttr('disabled');
} else {
$('button[type="submit"]').attr('disabled','disabled');
}
}
});
// validate login form on keyup and submit
$("#loginForm").validate({
rules: {
username: "required",
password: {
required: true,
minlength: 6
}
},
messages: {
username: {
required: "Please enter an username or email",
},
password: {
required: "Please provide a password",
minlength: "Password must exceed 6 characters"
}
},
submitHandler: function(form) {
if(loginForm.valid()){
form.submit();
$('button[type="submit"]').removeAttr('disabled');
} else {
$('button[type="submit"]').attr('disabled','disabled');
}
}
});
// propose username by combining first and lastname
$("#username").focus(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
if(firstName && lastName && !this.value) {
this.value = $.trim(firstName) + "." + $.trim(lastName);
}
});
});
</script>
<title>ESN</title>
</head>
<body>
<div class="front-card">
<div class="front-welcome">
<div class="front-welcome-text">
<h3>Welcome</h3>
</div>
</div>
<div class="front-login">
<g:form name="loginForm" controller="login" action="validate"
method="POST" class="form well well-small container-fluid span3.5">
<div id="login-form">
<div class="placeholding-login-username">
<input id="user-name" name="username"
value="${loginInstance?.username }"
placeholder="Username or email" class="input-xlarge" type="text"
maxlength="100" required/>
</div>
<div class="placeholding-login-password">
<input id="password" name="password"
value="${loginInstance?.password }"
placeholder="Password(min. length 6)" class="input-xlarge"
type="password" maxlength="30" required/>
</div>
<g:if test="${message}">
<div class="message text-error" role="status">
<ul class="errors" role="alert">
<li>
${message}
</li>
</ul>
</div>
</g:if>
<div class="button pull-right">
<button name="submit" class="btn" type="submit">Login</button>
</div>
</div>
</g:form>
</div>
<div class="front-signup">
<g:form name="signupForm" action="save" method="POST"
class="form well well-small container-fluid span3.5">
<div id="signup-form">
<fieldset class="form">
<legend>
<h5>
<strong class="muted">New to ESN?</strong> <strong
class="text-info"> Sign up</strong>
</h5>
</legend>
<div class="placeholding-first-name">
<input id="firstName" name="firstName"
value="${userInstance?.firstName}" placeholder="First name"
class="input-xlarge" type="text" maxlength="150" required/>
</div>
<div class="placeholding-last-name">
<input id="lastName" name="lastName"
value="${userInstance?.lastName}" placeholder="Last name"
class="input-xlarge" type="text" maxlength="150" required/>
</div>
<div class="placeholding-email-id">
<input id="emailId" name="emailId"
value="${userInstance?.emailId}" placeholder="Email Id(Corporate)"
class="input-xlarge" type="email" maxlength="100" required/>
</div>
<div class="placeholding-signup-username">
<input id="username" name="username"
value="${userInstance?.username}" placeholder="Username"
class="input-xlarge" type="text" maxlength="20" required/>
</div>
<div class="placeholding-signup-password">
<input id="password" name="password"
value="${userInstance?.password}"
placeholder="Password(min. length 6)" class="input-xlarge"
type="password" maxlength="30" required/>
</div>
</fieldset>
<fieldset class="button pull-right">
<button id="submit" name="submit" class="btn btn-primary" type="submit">Sign
up</button>
</fieldset>
<div>
<g:if test="${blankMessage}">
<div class="message text-error" role="status">
<ul class="errors" role="alert">
<li>
${blankMessage}
</li>
</ul>
</div>
</g:if>
<g:hasErrors bean="${userInstance}">
<div class="text-error">
<ul class="errors" role="alert">
<g:eachError bean="${userInstance}" var="error">
<li
<g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message
error="${error}" /></li>
</g:eachError>
</ul>
</div>
</g:hasErrors>
</div>
</div>
</g:form>
</div>
</div>
</body>
</html>
i want to remove or clear error message and reset jquery validation when i am click on cancel button.
here i have given my code :
$(document).ready(function() {
var validator = $("#loginForm").validate({
messages: {
email: {
required: "Please enter email.",
email: "Please enter a valid email."
},
password: "Please enter password."
}
});
<form name="loginForm" id="loginForm" method="post" action="javascript:login();">
<div class="login_contain_div">
<div id="login_errors" class="errors"></div>
<div class="login_contain_inner">
<span style="font-size: 20px; font-weight: lighter;">Email</span>
<input type="text" id="email" name="email" class="inputbg required email" />
<br/>
<span style="font-size: 20px; font-weight: lighter;">Password:</span>
<input type="password" id="password" name="password" class="inputbg required" />
</div>
<div class="login_button_area">
<input type="submit" id="login_submit" class="login_greenbtn button_float_left login_btn_width" name="submit" value="Ok" style="cursor: pointer;" />
<a class="ptr login_greenbtn button_float_right login_btn_width" onClick="$('#cboxClose').click();">Cancel</a>
</div>
</div>
</form>
use resetForm()
$(".cancel").click(function() {
validator.resetForm();
)};