Alerts conditional on model validation - javascript

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;
}
});

Related

How to solve blur and submit event simultaneous in angular

I have text box in my page, which i can enter 9 digit number. Onblur I am validating like the entered number is valid or not using API call, If service returns failure it will clear the text box with red border and form will be invalid. The event conflict happening between OnBlur and Submit. Submit service will call only the form is valid otherwise it will show toaster like enter mandatory filed.
If the text field focused and directly if I click on submit button, both event calling simultaneously and it is clearing the number field OnBlur as well as the service is calling.
Please can you help me to resolve this conflicts.
file.html
<form class="contact-form" #create="ngForm">
<div class="controls">
<input NumberOnly="true" type="text" id="num" [ngClass]="{'red-border-class': ((showErrorFlag == true && numberField.errors) || (showErrorFlag == true && numberField.errors && (numberField.dirty || numberField.touched)))}"
[disabled]="disableRotaDetailFields" [(ngModel)]="number"
class="floatLabel" name="ownership" required #numberField="ngModel" (blur)="validatenumber(number)" [maxLength]="einLength">
<label for="ein">number<sup>*</sup></label>
</div>
<button (click)="SaveData(create)">Save</button>
</form>
file.ts
public validatenumber(number) {
let reqObj = {
"ownership": number
}
this.calloutService.validateOwnerEin(reqObj)
.pipe(takeUntil(this.unsubscribe))
.subscribe((data) => {
}, (err) => {
if (err.status == 404) {
this.number = "";
}
this.toastr.error(err.overriddenMessage);
})
}
SaveData(){
if (!formFlag.valid ) {
this.showErrorFlag = true;
this.toastr.error('Please fill all the mandatory fields');
}else {
this.calloutService.createData(this.data)
.pipe(takeUntil(this.unsubscribe))
.subscribe(data => {
this.showSpinnerFlag = false;
let response = data;
if (data) {
this.toastr.success("Rota created successfully.");
} else {
this.toastr.error("Could not save.");
}
}, err => {
this.showSpinnerFlag = false;
this.toastr.error(err.overriddenMessage);
})
}
}

how to get parsley.js to validate if one of the fields has number with a with a minimum value equal to 1

I have Adults, Children and Babies fields on my form. All these 3 fields have a default value which is 0. I am using parsley to validate the form. I need parsley to validate if at least one of the fields has a value greater than 0. It's should validate the form if one of the fields is bigger then 0. If not it should give an error when trying to submit. I used this example from the parsley offical website.
This is what I have so far:
<input type="text" name="nAdults" id="nAdults" value="0" data-parsley-group="block1" class="form-control " />
<input type="text" name="nChildren" id="nChildren" value="0" data-parsley-group="block2" class="form-control "/>
<input type="text" name="nBabies" id="nBabies" value="0" data-parsley-group="block3" class="form-control " />
<script type="text/javascript">
//parsley validate
var form = $('#{{ $pageModule }}FormAjax');
form.parsley().on('form:validate', function (formInstance) {
var ok = formInstance.isValid({group: 'block1', force: true}) || formInstance.isValid({group: 'block2', force: true}) || formInstance.isValid({group: 'block3', force: true});
$('.invalid-form-error-message').html(ok ? '' : 'You must fill at least one of the Adult, Child or FOC Fields!').toggleClass('filled', !ok);
if (!ok)
formInstance.validationResult = false;
});
//form submit
form.on('submit', function(e) {
var f = $(this);
f.parsley().validate();
if (f.parsley().isValid()) {
var options = {
dataType: 'json',
beforeSubmit : showRequest,
success: showResponse
}
$(this).ajaxSubmit(options);
return false;
}
else {
return false; }
e.preventDefault();
});
</script>
I would appreciate if you can show me how to validate these 3 fields. When I write
data-parsley-min="1" it expects all the field to have a minimum value. But I need only one field to have minimum value "1".
you have to write custom validator. Here can you find a good example, how to do this.
my own working example (see console)
// bind event after form validation
$.listen('parsley:form:validated', function(ParsleyForm) {
// We only do this for specific forms
if (ParsleyForm.$element.attr('id') == 'myForm') {
var combinations = ParsleyForm.$element.find('input')
,counter=0;
$.each($('input'),function(){
counter+=($(this).val());
});
if(counter>0)
ParsleyForm.validationResult = true;
}
});

How to validate password from asp.net in js?

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();
});

How to use the Angular jQuery Validate's checkForm() function

EDIT:
I've added a JsFiddle so you can easily troubleshoot instead of having to set up the environment yourself. As you can see, validation is done on the Email field even before the blur event on the input element, which was triggered by the $scope.Email being changed. If you comment out the ng-show="!mainForm.validate()" on the <p> element, you'll see that the issue doesn't take place.
I am using the Angular implementation of jQuery Validate, and I am in need of the ability to check if a form is valid without showing the error messages. The standard solution I've seen online is to use jQuery Validate's checkForm() function, like this:
$('#myform').validate().checkForm()
However, the Angular wrapper I'm using doesn't currently implement the checkForm function. I have been trying to modify the source code to bring it in, and I'm afraid I'm in over my head. The code is small and simple enough that I'll paste it here:
(function (angular, $) {
angular.module('ngValidate', [])
.directive('ngValidate', function () {
return {
require: 'form',
restrict: 'A',
scope: {
ngValidate: '='
},
link: function (scope, element, attrs, form) {
var validator = element.validate(scope.ngValidate);
form.validate = function (options) {
var oldSettings = validator.settings;
validator.settings = $.extend(true, {}, validator.settings, options);
var valid = validator.form();
validator.settings = oldSettings; // Reset to old settings
return valid;
};
form.numberOfInvalids = function () {
return validator.numberOfInvalids();
};
//This is the part I've tried adding in.
//It runs, but still shows error messages when executed.
//form.checkForm = function() {
// return validator.checkForm();
//}
}
};
})
.provider('$validator', function () {
$.validator.setDefaults({
onsubmit: false // to prevent validating twice
});
return {
setDefaults: $.validator.setDefaults,
addMethod: $.validator.addMethod,
setDefaultMessages: function (messages) {
angular.extend($.validator.messages, messages);
},
format: $.validator.format,
$get: function () {
return {};
}
};
});
}(angular, jQuery));
I want to be able to use it to show or hide a message, like this:
<p class="alert alert-danger" ng-show="!mainForm.checkForm()">Please correct any errors above before saving.</p>
The reason I don't just use !mainForm.validate() is because that causes the error messages to be shown on elements before they are "blurred" away from, which is what I'm trying to avoid. Can anyone help me implement the checkForm() function into this angular directive?
You can add checkForm() function to the plugin as following.
(function (angular, $) {
angular.module('ngValidate', [])
.directive('ngValidate', function () {
return {
require: 'form',
restrict: 'A',
scope: {
ngValidate: '='
},
link: function (scope, element, attrs, form) {
var validator = element.validate(scope.ngValidate);
form.validate = function (options) {
var oldSettings = validator.settings;
validator.settings = $.extend(true, {}, validator.settings, options);
var valid = validator.form();
validator.settings = oldSettings; // Reset to old settings
return valid;
};
form.checkForm = function (options) {
var oldSettings = validator.settings;
validator.settings = $.extend(true, {}, validator.settings, options);
var valid = validator.checkForm();
validator.submitted = {};
validator.settings = oldSettings; // Reset to old settings
return valid;
};
form.numberOfInvalids = function () {
return validator.numberOfInvalids();
};
}
};
})
.provider('$validator', function () {
$.validator.setDefaults({
onsubmit: false // to prevent validating twice
});
return {
setDefaults: $.validator.setDefaults,
addMethod: $.validator.addMethod,
setDefaultMessages: function (messages) {
angular.extend($.validator.messages, messages);
},
format: $.validator.format,
$get: function () {
return {};
}
};
});
}(angular, jQuery));
Please find the updated jsFiddle here https://jsfiddle.net/b2k4p3aw/
Reference: Jquery Validation: Call Valid without displaying errors?
If I understand your question correctly, you want to be able to show an error message when the email adress is invalid and you decide you want to show the error message.
You can achieve this by setting the input type to email like this <input type=email>
Angular adds an property to the form $valid so you can check in your controller if the submitted text is valid. So we only have to access this variable in the controller and invert it. (Because we want to show the error when it is not valid)
$scope.onSubmit = function() {
// Decide here if you want to show the error message or not
$scope.mainForm.unvalidSubmit = !$scope.mainForm.$valid
}
I also added a submit button that uses browser validation on submit. This way the onSubmit function won't even get called and the browser will show an error. These methods don't require anything except angularjs.
You can check the updated JSFiddle here
Make sure to open your console to see when the onSubmit function gets called and what value gets send when you press the button.
You can use $touched, which is true as soon as the field is focused then blurred.
<p class="alert alert-danger" ng-show="mainForm.Email.$touched && !mainForm.validate()">Please correct any errors above before saving.</p>
you can achieve onblur event with ng-show="mainForm.Email.$invalid && mainForm.Email.$touched" to <p> tag
by default mainForm.Email.$touched is false, on blur it will change to true
for proper validation change the <input> tag type to email
you can add ng-keydown="mainForm.Email.$touched=false" if you don't want to show error message on editing the input tag
I didn't used angular-validate.js plugin
<div ng-app="PageModule" ng-controller="MainController" class="container"><br />
<form method="post" name="mainForm" ng-submit="OnSubmit(mainForm)" >
<label>Email:
<input type="email" name="Email" ng-keydown="mainForm.Email.$touched=false" ng-model="Email" class="email" />
</label><br />
<p class="alert alert-danger" ng-show="mainForm.Email.$invalid && mainForm.Email.$touched">Please correct any errors above before saving.</p>
<button type="submit">Submit</button>
</form>
</div>
Updated code : JSFiddle
AngularJs Form Validation
More info on Angular validation
Update 2
checkForm will return whether the form is valid or invalid
// added checForm, also adds valid and invalid to angular
form.checkForm = function (){
var valid = validator.form();
angular.forEach(validator.successList, function(value, key) {
scope.$parent[formName][value.name].$setValidity(value.name,true);
});
angular.forEach(validator.errorMap, function(value, key) {
scope.$parent[formName][key].$setValidity(key,false);
});
return valid
}
to hide default messages adding by jQuery validation plugin add below snippet, to $.validator.setDefaults
app.config(function ($validatorProvider) {
$validatorProvider.setDefaults({
errorPlacement: function(error,element) { // to hide default error messages
return true;
}
});
});
here is the modified plugin looks like
(function (angular, $) {
angular.module('ngValidate', [])
.directive('ngValidate', function () {
return {
require: 'form',
restrict: 'A',
scope: {
ngValidate: '='
},
link: function (scope, element, attrs, form) {
var validator = element.validate(scope.ngValidate);
var formName = validator.currentForm.name;
form.validate = function (options) {
var oldSettings = validator.settings;
validator.settings = $.extend(true, {}, validator.settings, options);
var valid = validator.form();
validator.settings = oldSettings; // Reset to old settings
return valid;
};
form.numberOfInvalids = function () {
return validator.numberOfInvalids();
};
// added checkForm
form.checkForm = function (){
var valid = validator.form();
angular.forEach(validator.successList, function(value, key) {
scope.$parent[formName][value.name].$setValidity(value.name,true);
});
angular.forEach(validator.errorMap, function(value, key) {
scope.$parent[formName][key].$setValidity(key,false);
});
return valid
}
}
};
})
.provider('$validator', function () {
$.validator.setDefaults({
onsubmit: false // to prevent validating twice
});
return {
setDefaults: $.validator.setDefaults,
addMethod: $.validator.addMethod,
setDefaultMessages: function (messages) {
angular.extend($.validator.messages, messages);
},
format: $.validator.format,
$get: function () {
return {};
}
};
});
}(angular, jQuery));
controller
app.controller("MainController", function($scope) {
$scope.Email = "";
$scope.url = "";
$scope.isFormInValid = false; // to hide validation messages
$scope.OnSubmit = function(form) {
// here you can determine
$scope.isFormInValid = !$scope.mainForm.checkForm();
return false;
}
})
need to have following on every input tag(example for email)
ng-show="isFormInValid && !mainForm.Email.$invalid "
if the form and email both are invalid the validation message shows up.
JSFiddle
try this code for validation this is the form
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<div class="form-group">
<input type="text" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }" ng-model="name" name="name" class="form-control" placeholder="{{ 'regName' | translate }}" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Your name is required.</p>
</div>
<div class="form-group">
<input type="tel" ng-class="{ 'has-error' : userForm.mob.$invalid && !userForm.mob.$pristine }" ng-model="mob" class="form-control" name="mob" ng-maxlength="11" ng-minlength="11" ng-pattern="/^\d+$/" placeholder="{{ 'regPhone' | translate }}" required>
<p ng-show="userForm.mob.$invalid && !userForm.mob.$pristine" class="help-block">Enter a valid number</p>
</div>
<div class="form-group">
<input type="email" ng-model="email" name="email" class="form-control" placeholder="{{ 'regEmail' | translate }}" required>
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<div class="form-group">
<input type="password" ng-model="pass" name="pass" class="form-control" placeholder="{{ 'regPass' | translate }}" minlength="6" maxlength="16" required>
<p ng-show="userForm.pass.$invalid && !userForm.pass.$pristine" class="help-block"> Too short Min:6 Max:16</p>
<input type="password" ng-model="repass" class="form-control" ng-minlength="6" placeholder="{{ 'regConPass' | translate }}" ng-maxlength="16" required>
</div>
<button class="loginbtntwo" type="submit" id="regbtn2" ng-disabled="userForm.$dirty && userForm.$invalid" translate="signUp" ></button>
</form>
You will need to modify the Angular Validate Plugin a bit. Here is a working version of your code in JSFiddle. Note the updated plugin code as well as a pair of modifications to your original code.
Updated plugin code simply adds this to validator.SetDefaults parameter:
errorPlacement: function(error,element) { return true; } // to hide default error message
Then we use a scope variable to hide/show the custom error message:
$scope.OnSubmit = function(form) {
if (form.$dirty) {
if (form.validate()) {
//form submittal code
} else {
$scope.FormInvalid = true;
}
}

Problems with validate jquery function

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.*/

Categories