I was trying to make a validation in my form with jquery, but it does not work the way it was supposed to and I have no idea why.
I have this function to make the validation:
function newLogin () {
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
if (username == "" || password.length<5){
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
});
return false;
}
else{
Parse.User.logIn(username, password, {
success:function(user){
console.log("login successfull");
if(checkEmail()){
console.log(checkEmail());
document.location.href = "Temas.html";
}
},
error: function(user, error){
console.log(error.message);
displayErrorDiv();
}
})
}
}
And i got this form
<form id = "popup-login-form">
<input type="email" name="email" placeholder="Email" id = "popup-login-email" class="popup-input first"/>
<div id="error-message-email" class="error">
</div>
<input type="password" name="password" placeholder = "Password" id="popup-login-password" class="popup-input"/>
<div id="error-message-password" class="error">
</div>
<button class="popup-button" id="popup-cancel">Cancel</button>
<button type="submit" class="popup-button" id="popup-submit">Login</button>
<div class="error-message-login" class="error">
</div>
</form>
And the weird part is that just does not work in my page. Here it works, for example: http://jsfiddle.net/xs5vrrso/
There is no problem with the code which you shared in jsfiddle but the above code you are using $(document).ready({function()}) inside a function which is of no use. Now the problem is that the method newLogin is not called on dom ready and thus this issue occurs.
Better keep the function call inside $(document).ready({function() newLogin() }) . Now you can also use submitHandler in validate to merge the if else conditions.
i make one example to you
jsfiddler example
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
//event listening onSubmit
$('form').submit(function(event){
var returnForm = true;
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
//Make your validation here
if (username == "" || password.length<5){
returnForm = false;
}
return returnForm; //Submit if variable is true
});
});
With jQuery when i get the
"TypeError: $(...).validate is not a function"
I change
$(..).validate
for
jQuery(..).validate
You have to include this validate file after jquery file.
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
Do not wrap the code under the if condition with $(document).ready(). Change the code to :
if (username == "" || password.length < 5){
$("#popup-login-form").validate({ // initialize the plugin
/*remaining code here*/
});
}
Also it is a good habit to trim the spaces around any input that you accept from the users. For e.g in your case please do the following:
var username = $.trim($("#popup-login-email").val());
var password = $.trim($("#popup-login-password").val());
/* $.trim() would remove the whitespace from the beginning and end of a string.*/
Related
I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)
I have this input:
aspx
<input type="password" id="password" name="password" data-fv-stringlength-min="5" class="form-control col-md-7 col-xs-12" required="required" pattern="password" title="Follow the password requirement"/>
js
if( pattern ){
var regex, jsRegex;
switch( pattern ){
case 'alphanumeric' :
regex = /^[a-zA-Z0-9]+$/i;
break;
case 'numeric' :
regex = /^[0-9]+$/i;
break;
case 'phone' :
regex = /^\+?([0-9]|[-|' '])+$/i;
break;
case 'password':
regex = /^(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "])+$/i;
break;
}
}
the password case doesn't works fine. when I click on the password field and type any letter, it stuck and I can't enter any letter !
edit
in aspx, i use the following script:
<!-- validator -->
<script>
// initialize the validator function
validator.message.date = 'not a real date';
// validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup':
$('form')
.on('blur', 'input[required], input.optional, select.required', validator.checkField)
.on('change', 'select.required', validator.checkField)
.on('keypress', 'input[required][pattern]', validator.keypress);
$('.multi.required').on('keyup blur', 'input', function() {
validator.checkField.apply($(this).siblings().last()[0]);
});
//$('#add_member_form').formValidation();
$('form').submit(function(e) {
e.preventDefault();
var submit = true;
// evaluate the form using generic validaing
if (!validator.checkAll($(this))) {
submit = false;
}
if (submit)
this.submit();
return false;
});
</script>
<!-- /validator -->
Note:
I am using free bootstrap template. therefore, all the code is written in the template and I try to edit it to suite my need and try to understand it.
Edit2 : pattern code is in validator.js "coming with the template"
var validator = (function($){
var message, tests;
message = {
invalid : 'invalid input',
email : 'email address is invalid',
tests = {
email : function(a){
if ( !email_filter.test( a ) || a.match( email_illegalChars ) ){
alertTxt = a ? message.email : message.empty;
return false;
}
return true;
},
text: function (a, skip) {
if( pattern ){ // pattern code },
number : function(a){ // number code // },
date : function(a){ // date code // },
Your issue is not clear, and need more details
First, choose a method
Actually, you have two options to get what you want to do.
HTML5, using a pattern attribute
Many input types are able to manage their own pattern
(like email, phone, password...)
You must specify the pattern into the attribute "pattern",
without delimiters /.../ (and options)
<input
type="password"
id="password"
name="password"
data-fv-stringlength-min="5"
class="form-control col-md-7 col-xs-12"
required="required"
pattern="^(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? \"])+$"
title="Follow the password requirement"/>
But be careful with escaping quotes that can collide with the attribute quotes
JS, from a control javascript
Since i don't understand what are ou doing with your 'incomplete' code (above in you post).
I suppose, you have defined some onKeyDown events on inputs to catch when user is writing and calling the actual code under a function ?
I don't see the required condition to match the inputs values !
Can you update your post with more details, and i'll update mine too.
If you choose to continue with you plugin
Okay, in concerne of your edit2, using i guess jquery.form.validator:
var validator = (function($){
var message, tests;
message =
{
invalid : 'invalid input',
email : 'email address is invalid',
};
tests =
{
// <input type="email">
email : function(a)
{
if( !email_filter.test( a ) || a.match( email_illegalChars ) )
{
alertTxt = a ? message.email : message.empty;
return false;
}
return true;
},
// this is for <input type="text">
text: function (a, skip)
{
if( pattern ){ // pattern code },
},
// this is for <input type="number">
number : function(a){ /* number code */ },
date : function(a){ /* date code */ },
};
Then, i think you have to add you password method to tests:
// this is for <input type="password">
password: function (a, skip)
{
if( pattern ){ /* pattern code */},
},
Or i propose to you, a more simple
And not plugin requiring solution, by reusing your original code
from your (first duplicate post) How to validate password field in bootstrap?
note: stop using removeClass(...).addClass(...), would prefer
short and relevant methods like toggleClass(classname, condition)
or switchClass(classbefore, classafter)
CSS
.invalid { color: red!important; } /* note this important flag is require to overwrite the .valid class */
.valid { color: lime; }
HTML hint
<div id="pswd_info">
<h4>Password requirements:</h4>
<ul>
<li id="letter" class="fa-warning"> At least <strong>one letter</strong></li>
<li id="capital"> At least <strong>one capital letter</strong></li>
<li id="number"> At least <strong>one number</strong></li>
<li id="special"> At least <strong>one special character</strong></li>
<li id="length"> Be at least <strong>8 characters</strong></li>
<li id="password"> Must contains at least <strong>8 characters</strong>, specials chars (#$!...) and numbers</li>
</ul>
</div>
</div>
Jquery
$("form input").on("keyup", function(event)
{
var invalidClass = "invalid";
var type = $(this).attr("type");
var val = $(this).val();
switch(type)
{
case "email": /* */ break;
case "phone": /* */ break;
case "number":
{
var smt = (/^\d$/i.test(val);
$('#number').toggleClass(invalidClass, smt);
break;
}
case "password":
{
var smt = (/^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/i.test(val);
$('#password').toggleClass(invalidClass, smt);
break;
}
}
}).on("focus", function()
{
$('#pswd_info').show();
}).on("blur", function()
{
$('#pswd_info').hide();
});
I am using https://jqueryvalidation.org/ to validate my form on the frontend. The basic "if field is empty - validate" works OK.
But I'd like to the submit button to be initially disabled until a valid email address has been entered. I'd like the button to become enabled as soon as the field becomes valid (on keypress).
So basically I just need to remove the 'btn-disabled' class once its valid.
I'm struggling with the jQuery to add this function/method. Would be grateful if someone can help out.
Heres a slightly simplifed version: http://codepen.io/dagford/pen/kXJpEZ
$(document).ready(function(){
$("#reset-form").validate({
rules: {
emailaddress: {
required: true,
email: true
}
},
messages: {
email: "Please enter a valid email address"
}
});
});
you can check if the form is valid after entering the email address. Keep you button disabled by default and remove the disabled attribute once you validate the form.
$("#emailaddress").on("blur", function(){
if($("#reset-form").valid())
{
$("#btn-reset").removeAttr("disabled");
}
});
Code Pen : http://codepen.io/anon/pen/YWLjKX?editors=1010
You have attr for this
$('#button1, #button2').attr("disabled", true);
Check this :
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') { // write your code for valid email here
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
I am using Happy.js and would like to show a message in a span/p element which will appear below the submit button when the user successfully fills out the form. I have the validation working, But can't seem to hook in the showing of the message. I tried my hand at it below, in the unhappy function! Thanks in advance...
<p>
<input type="submit" class="submit myButtons submitButton specificLink button button-block button-rounded button-large" name="submit" value="Submit" placeholder="">
</p>
<div id="results" class="results" style="text-align:center;">
<span>
<p class="success">Your message was sent succssfully!<br> I will be in touch as soon as I can.
</p>
</span>
</div>
var dd= $.noConflict();
dd(document).ready(function () {
dd('.success').hide();
dd('#frmContact').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#yourName': {
required: true,
message: 'Might we inquire your name'
},
'#email': {
required: true,
message: 'How are we to reach you sans email??',
test: happy.email // this can be *any* function that returns true or false
},
'#comments': {
required: true,
message: 'Please leave a message!',
}
},
unHappy: function () {
var yourName = dd('#yourName').val();
var email = dd('#email').val();
var comments = dd('#comments').val();
if (yourName && email && comments == true){
dd('.success').show();
}
},
});
});
Give this a try
function () {
var yourName = dd('#yourName').val();
var email = dd('#email').val();
var comments = dd('#comments').val();
if (yourName && email && comments == true){
dd('#results').show();
dd('.success').show();
}
I have an Picture model with various validations:
validates :title, presence: true
validates :caption, presence: true
validates :image, presence: true
validates :price, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 1000 }
validates_size_of :tag_list, :minimum => 3, :message => "please add at least three tags"
The tag list has to be submitted in a specific format: at least three tags, separated by a comma and a space: eg foo, bar, cats
I want to have an alert that tells the user to "please wait, we're uploading your image" - but only AFTER the model has passed ALL of the validations ( before the .save in the controller)
Is there a way of doing this in the controller, which I'd prefer, or do I have to use some javascript like:
$("form#new_picture").on("submit", function () {
if LOTS OF HORRIBLE REGEX ON FORM FIELDS {
MESSAGE HERE
return true;
} else {
return false;
}
});
OR Is there a way of doing this in the model, as part of an after_validation callback?
Any suggestions much appreciated. Thanks in advance.
I would build a JS function to extract the fields that I want to be validated.
Then create a custom AJAX controller action, which:
instantiates a new object with given params
call valid? on it without saving it
Then:
On failure, update the form with error messages
On success, I would return a custom ajax response to display the alert and start POSTing the real object.
I've realised that this isn't really possible through through the model or controller, and resorted to a combination of three validation processes:
Validations in the model
The simpleform client side validations gem - this is v good, it tests validity the moment a form field loses focus - "real time" validation.
And some additional javascript to alert with popups and errors, pasted below.
Hopefully this makes the form virtually un-submittable without the user knowing what's missing.
THE JS SOLUTION
FORM
<form id="new_pic" novalidate>
<p><input type="file" name="file" required></p>
<p><input type="string" name="name" placeholder="Name" required></p>
<p><input type="string" name="tags" placeholder="Tags" data-validation="validateTags"></textarea></p>
<p><textarea name="description" data-validation="validateDescription"></textarea></p>
<p><button type="submit">Submit</button>
</form>
JS
var Validator = function(form) {
this.form = $(form);
}
$.extend(Validator.prototype, {
valid: function() {
var self = this;
this.errors = {};
this.form.find('[required]').each(function() {
self.validateRequired($(this));
});
this.form.find('[data-validation]').each(function() {
var el = $(this),
method = el.data('validation');
self[method].call(self, el);
});
return $.isEmptyObject(this.errors);
},
validateRequired: function(input) {
if (input.val() === '') {
this.addError(input, 'is required');
}
},
validateDescription: function(input) {
if (input.val().length < 64) {
this.addError(input, 'must be at least 64 characters');
}
},
validateTags: function(input) {
var tags = input.val().split(/, ?/);
if (tags.length < 3) {
this.addError(input, 'must have at least 3 tags');
}
},
addError: function(input, error) {
var name = input.attr('name');
this.errors[name] = this.errors[name] || [];
this.errors[name].push(error);
input.after('<span class="error">' + error + '</span>');
}
});
$('form#new_pic').on('submit', function(event) {
event.preventDefault();
var form = $(this),
validator = new Validator(form);
form.find('.error').remove();
if (validator.valid()) {
// continue with upload
alert('Go!');
return true;
} else {
// complain
alert('Stop!');
return false;
}
});