I've well researched and used this, but I don't know it is still getting error.
I need to check if existing image exists then file attribute should skip validation and viceversa.
HTML COde:
<input type="file" name="image" id="image">
<input type="hidden" name="old_image" value="">
JQuery Validation Code:
$("#add_reference").validate({
rules: {
link: {
required: true,
},
image:{
//required: true,
required: function(element) {
if ($("#old_image").val() == '')
{
return true;
}
else
{
return false;
}
},
accept:"jpg,png,jpeg,gif"
},
},
messages: {
link: {
required: "Please enter link title",
},
image:{
required: "Please choose image",
accept: "Please choose valid image files",
},
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
error.insertAfter(element);
}
});
Can Anyone tell me where I am going wrong?
There is no id in your input tag,instead you should add id attribute.
<input type="hidden" name="old_image" id="old_image" value="">
and you are calling it by id
if ($("#old_image").val() == '')
<input type="file" name="image" id="image">
<input type="hidden" id="old_image" name="old_image" value="">
Your validation won't fire because it is always passing the test, you are testing if #old_image is empty and as you can see it is always empty, are you triggering an event after you upload your file???
You can do it with this event..
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$("#old_image").val(fileName);
});
});
I have a custom method
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
Here I am trimming whitespace and replacing any repeating whitespaces with only one. I am then validating to make sure there are only letters and spaces.
Is it possible to make it so the trimmed value is submitted with the form instead of what the user entered?
Use the submitHandler and you can make any action before submiting the form ,(form.submit())
See beleow a working snippet
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5,
lettersandspaces: true
},
"age": {
required: true,
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"age": {
required: "Please, enter your age",
}
},
submitHandler: function (form) { // for demo
var newName = $("#name").val().replace(/\s+/g, ' ').trim()
$("#name").val(newName);
$(form).valid();
alert("Name = '"+newName+"'");
// comment return and uncomment form.submit(
return false; //form.submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name :</label>
<input type="text" name="name" id="name" /><br><br>
<label for="age">Age : </label>
<input type="age" name="age" id="age" /><br><br>
<button type="submit">Submit</button>
</form>
In validation form by jquery. If you want change value input name before validate. Let try:
$('#form').validate({
rules: {
'name': {
normalizer: function(){
return $('#name').val().(/\s+/g, ' ').trim();
}
}
}
})
So I'm using Knockout 2.3 and Knockout Validation 2.0.2. I have a viewModel with a property that is an observableArray of custom javascript "objects" (HRAdmin). An HRAdmin has 3 properties that need validation. I've having a hard time with how to manage this type of situation. I've tried different things, but this is where the code sits at this point.
For the sake of brevity, I've stripped out all of the other properties of my viewModel that ARE validating just fine. But what this also tells me is none of my other code is interfering.
You can run and step through the code here and see that even when you leave all fields blank and click the "Go to Step 3" link, this line of code always results in the object being valid.
if (!obj[i].isValid())
It shouldn't be valid. Ideas/Suggestions??
// check validity of each object in array
ko.validation.rules['collectionValidator'] = {
validator: function(obj, params) {
for (var i = 0; i < obj.length; i++) {
if (!obj[i].isValid()) {
obj[i].notifySubscribers();
return false;
}
}
return true;
}
};
// validate a certain number of object exist in array
ko.validation.rules['minArrayLength'] = {
validator: function(obj, params) {
return obj.length >= params.minLength;
},
message: "Must have at least {0} {1}"
};
ko.validation.registerExtenders();
// HRAdmin "object"
function HRAdmin() {
this.FirstName = ko.observable("").extend({
required: true,
minLength: 1,
maxLength: 50
});
this.LastName = ko.observable("").extend({
required: true,
minLength: 1,
maxLength: 50
});
this.Email = ko.observable("").extend({
required: true,
minLength: 1,
maxLength: 100,
email: true
});
}
var viewModel = function() {
var self = this;
// Must be at least one HRAdmin and all fields of EACH HRAdmin must validate
self.HrAdmins = ko.observableArray([ko.validatedObservable(new HRAdmin())]).extend({
minArrayLength: {
params: {
minLength: 1,
objectType: "Account Manager"
},
message: 'Must specify at least one Account Manager'
},
collectionValidator: {
message: 'Please check the Account Manager information'
}
});
self.AddHrAdmin = function(data, event) {
self.HrAdmins.push(new ko.validatedObservable(new HRAdmin()))
};
self.GoToStep3 = function(data, event) {
// validate at least one HRAdmin and ALL fields on each are valid
if (!self.HrAdmins.isValid()) {
self.HrAdmins.notifySubscribers();
return;
}
// on to step 3 ...
};
};
ko.applyBindings(new viewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.2/knockout.validation.min.js"></script>
<div data-bind="foreach: HrAdmins">
<input type="text" placeholder="First Name" data-bind="value: FirstName" />
<input type="text" placeholder="Last Name" data-bind="value: LastName" />
<input type="text" placeholder="Email Address" data-bind="value: Email" />
</div>
<p data-bind="validationMessage: HrAdmins" class="validationMessage"></p>
Add Manager
Go to Step 3
So after a lot of trail and error I've found a solution. Not sure if it's the BEST solution, but it works fine.
I've gotten rid of ko.validation.rules['collectionValidator'] and added a validator grouping.
self.HrAdminsErrors = ko.validation.group(self.HrAdmins, {deep: true, live: true});
The operational code is at the following fiddle:
http://jsfiddle.net/3b3o87dy/6/
Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/
I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:
$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })
How do I add a custom rule to achieve this?
Thanks to the answer of redsquare I added a method like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
Now all you need to do to validate against any regex is this:
$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.
Edit
The pattern function is now the preferred way to do this, making the example:
$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })
https://cdnjs.com/libraries/jquery-validate
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js
You can use the addMethod()
e.g
$.validator.addMethod('postalCode', function (value) {
return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');
good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
<script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("EMAIL", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Email Address is invalid: Please enter a valid email address.");
$.validator.addMethod("PASSWORD",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
$.validator.addMethod("SUBMIT",function(value,element){
return this.optional(element) || /[^ ]/i.test(value);
},"You did not click the submit button.");
// Validate signup form on keyup and submit
$("#LOGIN").validate({
rules: {
EMAIL: "required EMAIL",
PASSWORD: "required PASSWORD",
SUBMIT: "required SUBMIT",
},
});
});
</script>
</head>
<body>
<div id="LOGIN_FORM" class="form">
<form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
<h1>Log In</h1>
<div id="LOGIN_EMAIL">
<label for="EMAIL">Email Address</label>
<input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
</div>
<div id="LOGIN_PASSWORD">
<label for="PASSWORD">Password</label>
<input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
</div>
<div id="LOGIN_SUBMIT">
<input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
</div>
</form>
</div>
</body>
</html>
No reason to define the regex as a string.
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
and
telephone: { required: true, regex : /^[\d\s]+$/, minlength: 5 },
tis better this way, no?
Extending PeterTheNiceGuy's answer a bit:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
This would allow you to pass a regex object to the rule.
$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });
Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.
Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:
$("password").rules("add", {
regex: [
/^[a-zA-Z'.\s]{8,40}$/,
/^.*[a-z].*$/,
/^.*[A-Z].*$/,
/^.*[0-9].*$/
],
'!regex': /password|123/
});
But implementing those would maybe be too much.
As mentioned on the addMethod documentation:
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.
I got it to work like this:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$(function () {
$('#uiEmailAdress').focus();
$('#NewsletterForm').validate({
rules: {
uiEmailAdress:{
required: true,
email: true,
minlength: 5
},
uiConfirmEmailAdress:{
required: true,
email: true,
equalTo: '#uiEmailAdress'
},
DDLanguage:{
required: true
},
Testveld:{
required: true,
regex: /^[0-9]{3}$/
}
},
messages: {
uiEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
minlength: 'Minimum 5 charaters vereist'
},
uiConfirmEmailAdress:{
required: 'Verplicht veld',
email: 'Ongeldig emailadres',
equalTo: 'Veld is niet gelijk aan E-mailadres'
},
DDLanguage:{
required: 'Verplicht veld'
},
Testveld:{
required: 'Verplicht veld',
regex: '_REGEX'
}
}
});
});
Make sure that the regex is between / :-)
You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use
$("#frm").validate({
rules: {
Textbox: {
pattern: /^[a-zA-Z'.\s]{1,40}$/
},
},
messages: {
Textbox: {
pattern: 'The Textbox string format is invalid'
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form id="frm" method="get" action="">
<fieldset>
<p>
<label for="fullname">Textbox</label>
<input id="Textbox" name="Textbox" type="text">
</p>
</fieldset>
</form>
This is working code.
function validateSignup()
{
$.validator.addMethod(
"regex",
function(value, element, regexp)
{
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
},
"Please check your input."
);
$('#signupForm').validate(
{
onkeyup : false,
errorClass: "req_mess",
ignore: ":hidden",
validClass: "signup_valid_class",
errorClass: "signup_error_class",
rules:
{
email:
{
required: true,
email: true,
regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/,
},
userId:
{
required: true,
minlength: 6,
maxlength: 15,
regex: /^[A-Za-z0-9_]{6,15}$/,
},
phoneNum:
{
required: true,
regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/,
},
},
messages:
{
email:
{
required: 'You must enter a email',
regex: 'Please enter a valid email without spacial chars, ie, Example#gmail.com'
},
userId:
{
required: 'Alphanumeric, _, min:6, max:15',
regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016"
},
phoneNum:
{
required: "Please enter your phone number",
regex: "e.g. +91-1234567890"
},
},
submitHandler: function (form)
{
return true;
}
});
}
we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.
<input type="text" name="myfield" regex="/^[0-9]{3}$/i" />
therefore we use the following snippet
$.validator.addMethod(
"regex",
function(value, element, regstring) {
// fast exit on empty optional
if (this.optional(element)) {
return true;
}
var regParts = regstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
// the parsed pattern had delimiters and modifiers. handle them.
var regexp = new RegExp(regParts[1], regParts[2]);
} else {
// we got pattern string without delimiters
var regexp = new RegExp(regstring);
}
return regexp.test(value);
},
"Please check your input."
);
Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).
PS: there is also bundled plugin for that, https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js
This worked for me, being one of the validation rules:
Zip: {
required: true,
regex: /^\d{5}(?:[-\s]\d{4})?$/
}
Hope it helps
$.validator.methods.checkEmail = function( value, element ) {
return this.optional( element ) || /[a-z]+#[a-z]+\.[a-z]+/.test( value );
}
$("#myForm").validate({
rules: {
email: {
required: true,
checkEmail: true
}
},
messages: {
email: "incorrect email"
}
});
Have you tried this??
$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })
Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.