Jquery Plugin not validating a form - javascript

I am using Jquery Plugin to validate an Edit form.The validation works fine with the Create Form but it does not work with the Edit form.
My HTML is
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="EditProviderDetailsForm" method="post">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">FIRST NAME:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="FirstName" data-bind="value:FirstName">
</div>
<label class="col-sm-4 labelfont errorMsg" id="Err_FirstName">Enter the first name</label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">CONTACT NUMBER:</label>
<div class="col-sm-6">
<input type="text" class="form-control" data- bind="value:ContactNumber" placeholder="Enter the Contact Number" id="ContactNumber" maxlength="13">
</div>
<label class="col-sm-4 labelfont errorMsg" id="Err_ContactNum">Enter the Contact Number</label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">EMAIL ADDRESS: </label>
<div class="col-sm-6">
<input type="text" class="form-control" data- bind="value:ContactEmail" placeholder="Enter your email address" id="EmailAddress">
</div>
<label class="col-sm-4 labelfont errorMsg" id="Err_EmailAddress">Enter the Email Address</label>
</div>
<div class="form-group">
<button type="submit" id="Update" class="btn btn-primary col-sm-1 col- sm-offset-4">Update</button>
<button type="button" id="Cancel" class="btn btn-primary col-sm- 1">Reset</button>
</div>
</form>
</div>
</body>
The JavaScript is
$(document).ready(function () {
jQuery.validator.addMethod("AcceptEmail", function (value, element) {
return this.optional(element) || /^([\w\d\-\.]+)#{1}(([\w\d\-]{1,67})| ([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z\d]{2,4})(\.[a-zA-Z\d] {2})?)$/.test(value);
});
$("#EditProviderDetailsForm").validate({
onfocusout: function (element, event) {
this.element(element);
},
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === '') {
return;
} else if (element.name in this.submitted) {
this.element(element);
}
},
rules:
{
FirstName: { required: true, minlength: 2, maxlength: 20 },
ContactNumber: { required: true, minlength: 10, maxlength: 10 },
ContactEmail: { required: true, AcceptEmail: true }
},
messages: {
FirstName: {
required: "Please enter your first name",
minlength: "Minimum 2 characters required",
maxlength: "Maximum 20 characters allowed"
},
ContactNumber: {
required: "Please enter your Contact Number",
minlength: "Enter a 10 digit contact number",
maxlength: "Enter a 10 digit contact number"
},
ContactEmail: {
required: "Please enter your Email Address",
AcceptEmail: "Please enter a valid email ID"
}
}
});
var Provider = {
SpecializationArray: ko.observableArray(Specialities),
ProviderID: ko.observable(Edit_data.ProviderID),
FirstName: ko.observable(Edit_data.FirstName),
ContactNumber: ko.observable(Edit_data.ContactNumber),
ContactEmail: ko.observable(Edit_data.ContactEmail)
}
ko.applyBindings(Provider);
});
My Scripts are getting loaded in _Layout page in the Shared folder of MVC.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="../../Content/bootstrap-theme.min.css" />
<link rel="stylesheet" href="../../Content/bootstrap.min.css" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" src="../../Scripts/jquery-2.1.3.min.js"> </script>
<script type="text/javascript" src="../../Scripts/jquery-ui-1.11.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Scripts/knockout-3.2.0.js"></script>
</head>
I am at a loss here.Please guide me in the right direction.There are no errors in the Console.

You've missed one of the basics unfortunately - jQuery Validate requires every input to have a name attribute. Simply copy all your id attributes to the name and your code will work.
This is described in the wiki for the library. Also in the documentation:
The name attribute is '''required''' for input elements, the
validation plugin doesn't work without it. Usually name and id
attributes should have the same value.

Related

jQuery Validation submits even though it's invalid in form

I believe my api addEventListener is effecting my page validation. The required field validator works perfectly. When I try the second condition that to meet the length requirement it shows the error validation but still submits the data to the api to update the database. Why is it still submitting even though it's not valid for the min length scenario?
formAddUrl.addEventListener('submit', function(e) {
e.preventDefault();
console.log("submitting add")
const formData = new FormData(this);
fetch('/OfficerUrl/AddOfficerPararameter', {
method: 'post',
body: formData,
});
});
formUpdateUrl.addEventListener('submit', function(e) {
e.preventDefault();
console.log("submitting update")
const formData = new FormData(this);
fetch('/OfficerUrl/UpdateOfficerPararameter', {
method: 'post',
body: formData,
});
});
var beginAddValidator = $("form[name='formAddUrl']").validate({
rules: {
OfficerId: {
number: true,
required: true,
range: [0, 9999999]
},
OfficerUrl: {
required: true,
minlength: 5
}
},
messages: {
OfficerId: "Please enter a Officer Id.",
OfficerUrl: {
required: "Please enter a Officer Url.",
minlength: "Url must be at least 5 characters long."
}
},
});
var beginUpdateValidator = $("form[name='formUpdateUrl']").validate({
rules: {
OfficerUrl: {
required: true,
minlength: 5
}
},
messages: {
OfficerUrl: {
required: "Please enter a Officer Url.",
minlength: "Url must be at least 5 characters long."
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js" integrity="sha512-37T7leoNS06R80c8Ulq7cdCDU5MNQBwlYoy1TX/WUsLFC2eYNqtKlV0QjH7r8JpG/S0GUMZwebnVFLPd6SU5yg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<form id="formAddUrl" name="formAddUrl" method="post">
<div>
<label for="OfficerId" class="col-sm-6 control-label cleanPadding">Loan Officer ID</label>
<input name="OfficerId" id="OfficerId" class="form-control" placeholder="Officer Id" type="number" required />
</div>
<div>
<label for="OfficerUrl" class="col-sm-6 control-label cleanPadding">Officer Url</label>
<input name="OfficerUrl" id="OfficerUrl" class="form-control" placeholder="New" type="text" required />
</div>
<button type="submit" class="btn btn-primary btn-submit" name="add" style="width: 73px;">Add</button>
</form>
<form id="formUpdateUrl" name="formUpdateUrl" method="post">
<div>
<label class="col-sm-6 control-label cleanPadding"> Officer Url</label>
<input id="currentUrl" class="form-control" placeholder="Current" disabled />
</div>
<div>
<label for="OfficerUrl" class="col-sm-6 control-label cleanPadding">New Loan Officer Url</label>
<input name="OfficerUrl" id="newUrl" class="form-control" placeholder="New" />
</div>
<button type="submit" class="btn btn-primary btn-submit" name="update">Update</button>
</form>

Password change jQuery validation error message does not appear

I face a problem when I enter wrong matching password - the jQuery validation error message not appear.
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#passwordchange').validate({
rules:{
newpass:{
required: true
},
retypepass:{
required:true,
equalto: '#newpassword'
}
},
messages:{
retypepass:{
equalto:"should enter matching pass"
}
}
});
Here is the full code on codepen
AS #Azametzin's comment and the document, You should use equalTo instead of equalto
Syntax
equalTo( other ) Returns: Boolean
Description: Requires the element
to be the same as another one
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#passwordchange').validate({
rules:{
newpass:{
required: true
},
retypepass:{
required:true,
equalTo: '#newpassword'
}
},
messages:{
retypepass:{
equalTo:"should enter matching pass"
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.1/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<form method="GET" action="" id="passwordchange">
<div class="form-row">
<div class="form-group row no-gutters col-12">
<label for="newpassword" class="col-md-3">كلمة المرور الجديدة</label>
<div class="col-md-9">
<input type="password" class="form-control" id="newpassword" name="newpass" placeholder="GHIBKL#$*132581">
</div>
</div>
</div>
<div class="form-row">
<div class="form-group row no-gutters col-12">
<label for="retype" class="col-md-3">إعادة كلمة المرور</label>
<div class="col-md-9">
<input type="password" class="form-control" id="retype" name="retypepass" placeholder="GHIBKL#$*132581">
</div>
</div>
</div>
<button type="submit">submit</button>
</form>

How to reset Jquery remote validation

I am very new to Javascript and all. I am working on a registration page right now. I used a template given by my friends and I am trying to make it work with Laravel 5.3.
What I am trying to achieve here is: to validate if the email has already in the database. Now the validation works. It tells if the email exists or not. But once done that, no matter how user changes email input, it always show that the email has been taken.
var form = $(".form-signup");
$('#submit-form').click(function(e) {
form.validate({
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true,
remote: {
url: "/check/",
type: "get"
}
},
password: {
required: true,
minlength: 6,
maxlength: 16
},
password2: {
required: true,
minlength: 6,
maxlength: 16,
equalTo: '#password'
},
terms: {
required: true
}
},
messages: {
name: {
required: 'Enter your first name',
minlength: 'Enter at least 3 characters or more'
},
email: {
required: 'Enter email address',
email: 'Enter a valid email address',
remote: 'Email has been taken'
},
password: {
required: 'Write your password',
minlength: 'Minimum 6 characters',
maxlength: 'Maximum 16 characters'
},
password2: {
required: 'Write your password',
minlength: 'Minimum 6 characters',
maxlength: 'Maximum 16 characters',
equalTo: '2 passwords must be the same'
},
terms: {
required: 'You must agree with terms'
}
},
errorPlacement: function(error, element) {
console.log(element);
if (element.is(":radio") || element.is(":checkbox")) {
element.closest('.option-group').after(error);
} else {
error.insertAfter(element);
}
}
});
e.preventDefault();
if (form.valid()) {
$(this).addClass('ladda-button');
var l = Ladda.create(this);
l.start();
setTimeout(function() {
//AJAX added.
var formData = {
_token:$(this).data('token'),
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val(),
password_confirmation: $('#password2').val()
};
$.ajax({
type: 'POST',
url: '/register',
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: formData,
dataType: 'json',
statusCode: {
200: function (data) {
console.log('success');
console.log(data);
},
500: function (data) {
console.log(data);
}
}
});
}, 2000);
} else {
alert('not valid');
}
});
}
Here is my front end
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="" name="description" />
<meta content="themes-lab" name="author" />
<meta name="csrf_token" content="{{ csrf_token() }}" />
<link rel="shortcut icon" href="{{asset('admin_assets/images/favicon.png')}}">
<link href="{{asset('admin_assets/css/style.css')}}" rel="stylesheet">
<link href="{{asset('admin_assets/css/ui.css')}}" rel="stylesheet">
<link href="{{asset('admin_assets/plugins/icheck/skins/all.css')}}" rel="stylesheet"/>
<link href="{{asset('admin_assets/plugins/bootstrap-loading/lada.min.css')}}" rel="stylesheet">
</head>
<body class="account separate-inputs boxed" data-page="signup">
<!-- BEGIN LOGIN BOX -->
<div class="container" id="login-block">
<div class="row">
<div class="col-sm-6 col-md-6 col-md-offset-3">
<div class="account-wall">
<i class="user-img icons-faces-users-03"></i>
<form class="form-signup" role="form">
<div class="append-icon">
<input type="text" name="name" id="name" class="form-control form-white name" placeholder="Name" required autofocus>
<i class="icon-user"></i>
</div>
<div class="append-icon">
<input type="email" name="email" id="email" class="form-control form-white email" placeholder="Email" required>
<i class="icon-envelope"></i>
</div>
<div class="append-icon">
<input type="password" name="password" id="password" class="form-control form-white password" placeholder="Password" required>
<i class="icon-lock"></i>
</div>
<div class="append-icon m-b-20">
<input type="password" name="password2" id="password2" class="form-control form-white password2" placeholder="Repeat Password" required>
<i class="icon-lock"></i>
</div>
<div class="terms option-group">
<label for="terms" class="m-t-10">
<input type="checkbox" name="terms" id="terms" data-checkbox="icheckbox_square-blue" required/>
I agree with terms and conditions
</label>
</div>
<button type="submit" id="submit-form" class="btn btn-lg btn-dark m-t-20" data-style="expand-left">Register</button>
<div class="clearfix">
<p class="pull-right m-t-20">Already have an account? Sign In</p>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- END LOCKSCREEN BOX -->
<script src="{{asset('admin_assets/plugins/jquery/jquery-1.11.1.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/jquery/jquery-migrate-1.2.1.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/gsap/main-gsap.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/bootstrap/js/bootstrap.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/icheck/icheck.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/backstretch/backstretch.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/bootstrap-loading/lada.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/jquery-validation/jquery.validate.min.js')}}"></script>
<script src="{{asset('admin_assets/plugins/jquery-validation/additional-methods.min.js')}}"></script>
<script src="{{asset('admin_assets/js/plugins.js')}}"></script>
<script src="{{asset('admin_assets/js/pages/login-v1.js')}}"></script>
</body>
</html>
So basically, once a user input a used email and receives error message, they won't be able to proceed and the button will keep spinning.
Screenshot on the problem
Can any one suggests any possible solutions? It will be great to fix this problem. Thanks!
Yay, I finally figured out myself after plenty of researching.
The reason being, jQuery validation does NOT wait for remote response. That is why the program runs even if a email is already taken.
To solve this, just simply add
async: false
in the remote. and it will work just fine!

jquery validation with php form

I am trying to use jquery validation for a php form to change your password but I keep getting the error "Your password must be the same as above" when the password is correct. I can't seem to find out where I have went wrong at all... Here's the JS code
var changepassword = function() {
return {
init: function() {
/*
* Jquery Validation, https://github.com/jzaefferer/jquery-validation
*/
$('#changepassword').validate({
errorClass: 'help-block animation-slideUp',
errorElement: 'div',
errorPlacement: function(error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function(e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function(e) {
if (e.closest('.form-group').find('.help-block').length === 2) {
e.closest('.help-block').remove();
} else {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
}
},
rules: {
'newpassword': {
required: true,
minlength: 6
},
'newpassword-verify': {
equalTo: '#newpassword',
required: true
}
},
messages: {
'newpassword': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long'
},
'newpassword-verify': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
};
}();
This is the PHP/HTML for the form
<form method="POST" class="form-horizontal form-bordered" id="changepassword">
<div class="form-group">
<label class="col-md-3 control-label" for="newpassword">New Password</label>
<div class="col-md-6">
<input type="password" id="newpassword" name="newpassword" class="form-control" placeholder="New Password" required>
</div>
</div>
<!-- This is where I keep getting the error -->
<div class="form-group">
<label class="col-md-3 control-label">Repeat Password</label>
<div class="col-md-6">
<input type="password" id="newpassword-verify" name="newpassword-verify" class="form-control" placeholder="Repeat Password" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Current Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group form-actions">
<button type="submit" name="update" class="btn btn-block btn-primary">Update</button>
</div>
</form>
Sorry, I was able to fix it by making a new file called settings1.php then removing the old one and renaming the new one with the old name.

Validation plugin files are not working

I am doing my form validation with jquery validation plugin. Everything seems fine but its not working. No message appears. Or may be its due to files that I have included.
files included
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
here is jquery
<script type="text/javascript">
$(function($){
$("#joinform").validate({
rules: {
firstname: {
required: true,
maxlength: 30
},
lastname: {
required: true,
maxlength: 30
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 6
},
repassword: {
required: true,
equalTo: "#password"
}
},
messages: {
firstname: {
required: "Please enter your firstname",
maxlength: "Firstname is too large"
},
lastname: {
required: "Please enter your lastname",
maxlength: "Lastname is too large"
},
email: {
required: "Please enter email address",
email: "Please enter the valid email"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long"
},
repassword: {
required: "Please confirm your password",
equalTo:"Passwords should be same"
}
}
});
});
</script>
here is html.
<form role="form" name="joinform" id="joinform" action="" method="post">
<div class="form-group">
<label for="name">Name: </label>
<input type="text" class="form-control" name="firstname" placeholder="First Name" required/>
<input type="text" class="form-control" name="lastname" placeholder="Last Name" required/>
<br/>
<label for="email">Email: </label>
<input type="email" class="form-control" name="email" placeholder="Enter email" required email/>
<br/>
<label for="pwd">Password: </label>
<input type="password" class="form-control" name="password" placeholder="at least 6 characters long" required/>
<label for="repass">Retype-Password:</label>
<input type="password" class="form-control" name="repassword" placeholder="Confirm your password" required/>
<br/>
Already a member?Login<br/>
<br/>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
When using any jQuery plugin, you must load jQuery first. You are also including the plugin twice. You must not include each plugin more than once... preferably use the latest version.
This is correct...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
Otherwise, use the latest plugin version supported by your version of jQuery...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>

Categories

Resources