JQuery Validation matching fields - javascript

I am developing a project with a registration form. I have 2 email fields as well as 2 password fields, each need to match each other. I am using JQuery validate and Bootstrap in an ASP.NET MVC 4 (C#) framework. Even if they are matching, the fields are getting the error that they do not match.
HTML
Registration Form
<div class="row">
<form id="formRegister" class="form-horizontal col-xs-5">
<div class="form-group">
<label for="textFirstName" class="control-label col-xs-2">First name</label>
<div class="col-xs-4">
<input type="text" name="textFirstName" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<label for="textLastName" class="control-label col-xs-2">Last name</label>
<div class="col-xs-4">
<input type="text" name="textLastName" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<label for="textEmail" class="control-label col-xs-2">Email</label>
<div class="col-xs-4">
<input type="text" name="textEmail" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<label for="textEmail2" class="control-label col-xs-2">Reenter email</label>
<div class="col-xs-4">
<input type="text" name="textEmail2" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<label for="passwordPW1" class="control-label col-xs-2">Password</label>
<div class="col-xs-4">
<input type="password" name="passwordPW1" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<label for="passwordPW2" class="control-label col-xs-2">Reenter Password</label>
<div class="col-xs-4">
<input type="password" name="passwordPW2" class="form-control" />
</div>
<div class="col-xs-6"></div>
</div>
<div class="form-group">
<div class="btn-group col-xs-offset-2 col-xs-5">
<button type="submit" class="btn btn-info">Submit</button>
<button type="reset" class="btn btn-info">Clear</button>
</div>
</div>
</form>
</div>
JS
jQuery(function ($) {
$('#formRegister').validate({
errorElement: "div",
errorPlacement: function(error, element) {
error.appendTo(element.parent("div").next("div"));
},
rules: {
textFirstName: {
required: true,
minlength: 1,
maxlength: 50
},
textLastName: {
required: false,
maxlength: 50
},
textEmail: {
required: true,
email: true
},
textEmail2: {
equalTo: "#textEmail"
},
passwordPW1: {
required: true,
minlength: 4
},
passwordPW2: {
equalTo: "#passwordPW1"
}
},
messages: {
textFirstName: "The first name must be from 1 to 50 characters in length",
textLastName: "The last name must be from 0 to 50 characters in length",
textEmail: "Please enter a valid email address",
textEmail2: "Emails do not match",
passwordPW1: "The password must be from 4 to 50 characters in length",
passwordPW2: "Passwords do not match"
},
highlight: function (element) {
$(element).closest('next').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.next').removeClass('error').addClass('success');
},
submitHandler: function (form) {
form.submit();
}
});
});

Your problem is that you're referring to selectors that don't match anything. For instance, #textEmail (used in the equalTo property) won't match anything in your current DOM.
Replace this line:
<input type="text" name="textEmail" class="form-control" />
With this line:
<input type="text" id="textEmail" name="textEmail" class="form-control" />
Alternatively, you can use a different selector in your equalTo property:
// ...
rules: {
// ...
textEmail2: {
equalTo: "[name=textEmail]"
},
// ...

Your validation for equalTo currently is
textEmail2: {
equalTo: "#textEmail"
}
but the input textEmail has no id="textEmail". Try to add this id and it should work then.
The same applies to other validation rules where you match against ids that are not yet added at the inputs.

I don't know anything about .asp.net and bootstrap, but
in your form, you are using the name tag, while in your javascript,
you are using a #, which refers to an ID.
Give your input an the id textEmail and passwordPW1

Related

jQuery validation for minimum and maximum length is not working with Bootstrap 4

I cannot get the jQuery plugin to validate minlength and maxlength. I cannot see the error message that the minimum length or maximum length as I specify. The contact form and the jQuery code of the contact form are as follows:
The contact form:
<form id="contactForm" class="contact-form" action="form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4" id="contactSuccess">
<strong>Success!</strong> Message sent!.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4" id="contactError">
<strong>Error!</strong> There was an error.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Name</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
</div>
<div class="form-row">
<div class="form-group col">
<label class="font-weight-bold text-dark">Phone</label>
<input type="text" value="" data-msg-required="Please enter your phone number." maxlength="100" class="form-control" name="subject" id="subject" required>
</div>
</div>
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Email</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input type="submit" value="Send Message" class="btn btn-primary btn-modern" data-loading-text="Loading...">
</div>
</div>
</form>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/additional-methods.js"></script>
Jquery and Javascripts links:
<script>
jQuery(function ($) {
$("#contactForm").validate({
errorClass: "error fail-alert",
validClass: "valid success-alert",
rules: {
name : {
required: true,
minlength: 3
},
phone: {
required: true,
number: true,
minlength: 8
},
email: {
required: true,
email: true
},
}
});
});
</script>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
Validation works, but minimum and maximum length are not working, and the error messages do not capture that; alternatively, it gives me a green tick (i.e., validated). I am not sure what is the reason for that.

How to change only error message color of input form-control

I am trying to style my first website.
I am using Bootstrap 4 and the jquery validation plugin and I am doing a form right now. I have two problems:
First, I only want to change the color of the error message below my input, but my styling changes the input text size/color and the error message text size/color, how can I only change error text below an input?
Second question is, where in my code do I change the Bootstrap form control state, depending on valid or not?
This is my code so far:
$('document').ready(function(){
$('#registration_form').validate({
rules: {
username: {
required: true,
maxlength: 10,
minlength: 3
},
email: {
required: true,
email: true
},
email_con: {
required: true,
equalTo: "#email"
},
password: {
required: true,
minlength: 7
},
password_con: {
required: true,
equalTo: "#password"
},
formCheck: {
required: true
},
}
});
});
.error{
color: red;
font-Size: 13px;
}
<div class="form-row form-group">
<div class="col-sm-4 col-xl-3 text-center d-xl-flex justify-content-xl-center align-items-xl-center label-column"><label class="col-form-label">Email* :</label></div>
<div class="col-sm-6 input-column"><input class="form-control" type="email" name="email" id="email" placeholder="name#mail.com"></div>
</div>
If you want to change color of error text message only then write like label.error{color: red;} and follow below html structure.
$(document).ready(function(){
$('#registration_form').validate({
rules: {
email: {
required: true,
email: true
}
}
});
});
label.error{
color: red;
font-size: 13px;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<div class="container my-2">
<div class="row">
<form class="col-sm-12" action="#" id="registration_form">
<div class="form-row form-group">
<div class="col-sm-4 text-sm-right">
<label class="col-form-label" for="email">Email* :</label>
</div>
<div class="col-sm-6">
<input class="form-control" type="email" name="email" id="email" placeholder="name#mail.com">
</div>
</div>
<div class="form-row form-group">
<div class="col-sm-6 offset-sm-4">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
There are classes to deal with validaiton when it comes to bootstrap usage. Try like this
<div class="container">
<p class="h1">Register</p>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email"
placeholder="E-mail" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
The e-mail is required!
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6">
<div class="valid-feedback">
Great!
</div>
<div class="invalid-feedback">
The password must contain at least 6 characters!
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>
<script>
(function() {
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
You can run a snippet in full page and check this answer
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<p class="h1">Register</p>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email"
placeholder="E-mail" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
The e-mail is required!
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6">
<div class="valid-feedback">
Great!
</div>
<div class="invalid-feedback">
The password must contain at least 6 characters!
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>
<script>
(function() {
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>

How to show error message from ajax response of api?

i have sent api request using jquery ajax i am getting ajax response like this
Array ( [consumer_key] => ada691a715307861907d65d36d [consumer_secret] => a75e40ec1530786190b62316d1 [consumer_nonce] => 1537011049789 [consumer_device_id] => ldx0EWMCl3hNhJWCRIdPVveLy [consumer_url] => processregistration ) {"success":"0","data":[],"message":"Email address is already exist"}
i would like to show error message if response contains "Email address is already exist" otherwise alert Message shuold be successfully submitted
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
var customers_firstname=$("#customers_firstname").val();
var customers_lastname=$("#customers_lastname").val();
var customers_telephone=$("#customers_telephone").val();
var email=$("#email").val();
var d = new Date();
var consumer_nonce = d.getTime();
U=url+'api/save_reg';
//alert(consumer_nonce);
//exit;
//var ul="{{ url('/backend/api/save_reg') }}";
$.ajax({
type:"POST",
url:url+'api/save_reg',
data:$("#postcontent").serialize(),
/* data:{
customers_firstname:customers_firstname,
customers_lastname:customers_lastname,
customers_telephone:customers_telephone,
email:email,
password:password
},*/
headers: {
"consumer-key": consumer_key,
"consumer-secret": consumer_secret,
"consumer-nonce": consumer_nonce,
"consumer-device-id": consumer_device_id,
},
beforeSend:function(){
$(".post_submitting").show().html("<center><img src='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.16.1/images/loader-large.gif'/></center>");
},success:function(response){
alert(response);
//-- alert(response[1]);
//alert(response);
//response = response.toJSON();
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
}
});
#extends('frontend.layouts.app')
#section('title','Home')
#section('body')
<!-- Main Container -->
<div class="main-container container">
<ul class="breadcrumb">
<li><i class="fa fa-home"></i></li>
<li>Account</li>
<li>Register</li>
</ul>
<div class="row">
<div id="content" class="col-sm-12">
<h2 class="title">Register Account</h2>
<p>If you already have an account with us, please login at the login page.</p>
<div id="return_update_msg" class="return_update_msg">j</div>
<div class="post_submitting"></div>
<form name="postcontent" class="cmxform" id="postcontent" >
<fieldset id="account">
<legend>Your Personal Details</legend>
<div class="form-group required">
<label class="col-sm-2 control-label" for="customers_firstname">First Name</label>
<div class="col-sm-10">
<input type="text" name="customers_firstname" minlength="2" placeholder="First Name" id="customers_firstname" class="form-control">
<span id="customers_firstname_error"></span>
</div>
</div>
<div class="form-group required">
<label class="col-sm-2 control-label" for="customers_lastname">Last Name</label>
<div class="col-sm-10">
<input type="text" name="customers_lastname" minlength="2" placeholder="Last Name" id="customers_lastname" class="form-control">
<span id="customers_lastname_error"></span>
</div>
</div>
<div class="form-group required">
<label class="col-sm-2 control-label" for="email">E-Mail</label>
<div class="col-sm-10">
<input type="email" name="email" placeholder="E-Mail" id="email" class="form-control">
<span id="email_error"></span>
</div>
</div>
<div class="form-group required">
<label class="col-sm-2 control-label" for="input-telephone">Mobile Number</label>
<div class="col-sm-10">
<input type="tel" name="customers_telephone" placeholder="Telephone" id="customers_telephone" class="form-control">
<span id="customers_telephone_error"></span>
</div>
</div>
</fieldset>
<fieldset>
<legend>Your Password</legend>
<div class="form-group required">
<label class="col-sm-2 control-label" for="password">Password</label>
<div class="col-sm-10">
<input type="password" name="password" placeholder="Password" id="password" class="form-control">
<span id="password_error"></span>
</div>
</div>
<div class="form-group required">
<label class="col-sm-2 control-label" for="confirm_password">Password Confirm</label>
<div class="col-sm-10">
<input type="password" name="confirm_password" placeholder="Password Confirm" id="confirm_password" class="form-control">
<span id="password_confirm_error"></span>
</div>
</div>
</fieldset>
<span id="success_message"></span>
<div class="buttons">
<input class="submit btn btn-primary" id="save_buttonk" type="submit" value="Submit">
<!--<input type="submit" id="save_button" value="Continue" class="btn btn-primary">-->
</div>
</form>
</div>
</div>
</div>
<br />
<!-- //Main Container -->
#endsection
#section('pagescript')
<script type="text/javascript" src="{{ asset('public/frontend/qshopee')}}/js/registration.js"></script>
<script>
$().ready(function() {
// validate the comment form when it is submitted
$("#commentForm").validate();
// validate signup form on keyup and submit
$("#postcontent").validate({
rules: {
//customers_firstname: "required",
//customers_lastname: "required",
/*username: {
required: true,
minlength: 2
},*/
customers_firstname: {
required: true,
minlength: 2
},
customers_lastname: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
/*topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"*/
},
messages: {
//customers_firstname: "Please enter your firstname",
//customers_lastname: "Please enter your lastname",
/*username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},*/
customers_firstname: {
required: "Please enter a firstname",
minlength: "Your firstname must consist of at least 2 characters"
},
customers_lastname: {
required: "Please enter a lastname",
minlength: "Your lastname must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address"
/*agree: "Please accept our policy",
topic: "Please select at least 2 topics"*/
}
});
});
</script>
#stop
try
if (response.indexOf('Email address is already exist') > -1)
{
alert("Email Already Registered");
}
else
{
alert("Registration Successful");

Form validation styles not working

I've been experimenting with JQuery form validation, but haven't been able to get success/failure classes to be added once the validation has been complete.
Here is my code:
https://jsfiddle.net/5WMff/
<form method = "post" id = "signUpForm">
<div class="modal-body">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="surname">Surname:</label>
<input type="text" class="form-control" name="surname" >
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number:</label>
<input type="phone" class="form-control" name="phoneNumber">
</div>
<div class="form-group">
<label for="postalCode">Home Postcode:</label>
<input type="text" class="form-control" name="postalCode">
</div>
<div class="checkbox">
<label><input type="checkbox" name = "acceptTCs">Accept Terms and Conditions</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Back</button>
<input type = "submit" name = "submit" class = "btn btn-success btn-large" value = "Submit" ></button>
</div>
</form>
JS:
$(document).ready(function () {
$('#signUpForm').validate({
rules: {
firstName: {
minlength: 2,
required: true
},
surname: {
required: true,
email: true
},
email: {
minlength: 2,
required: true
},
phoneNumber: {
minlength: 7,
required: true
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.form-group').removeClass('error').addClass('success');
}
});
});
The validation (OK vs. more info required) is working fine, it's just failing to add the success/failure class as well. I know it's something obvious I've missed out, but have come to a bit of a dead end.
The effect I'm looking for is like here: http://jsfiddle.net/5WMff/
Thanks.
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
Use submitHandler . Hope this will help you.

jQuery Validation not getting options

I'm trying to customise my form validation with no success.
Nor message nor custom error class is firing when I test. Still, it seems to work, since it shows the standard error message after the invalid field.
My code:
HTML
<form role="form" method="POST" id="account-edit">
<div class="box-body">
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Endereço">
</div>
<div class="form-group">
<label for="telephone">Telephone</label>
<input type="text" class="form-control" id="telephone" name="telephone" placeholder="Telefone">
</div>
<div class="form-group">
<label for="telephone">Contact-email</label>
<input type="email" class="form-control" id="email" name="contact_email" placeholder="E-mail">
</div>
<div class="form-group">
<label for="telephone">Website</label>
<input type="text" class="form-control" id="website" name="website" placeholder="Website" >
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update Info</button>
</div>
</form>
Javascript:
$('#account-edit').validate({
errorClass: "has-error",
rules: {
email: {
email: true
}
},
messages: {
email: {
email: 'Please enter a valid email format: name#domain'
}
},
highlight: function(element, errorClass) {
$(element).closest('.control-group').addClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).closest('.control-group').removeClass(errorClass);
}
});
CSS:
.has-error input {
border: 1px solid red;
}
A JSFiddle with my code: http://jsfiddle.net/ov8zx694/1/
Also, I managed to customize the error message through data-attributes.
The rules object can only be constructed using the name attribute. In your case, the name is contact_email, not email...
rules: {
contact_email: {
email: true
}
},
messages: {
contact_email: {
email: 'Please enter a valid email format: name#domain'
}
},
DEMO: http://jsfiddle.net/ov8zx694/2/
Also, the CSS is not working because you don't have any markup that contains the control-group class.
$(element).closest('.control-group').addClass(errorClass);
Either change the markup so that it contains this class or change the class name to something that's already in your markup...
$(element).closest('.form-group').addClass(errorClass);
DEMO 2: http://jsfiddle.net/ov8zx694/3/

Categories