How to trigger a custom validation if value exists in input field using jquery validate? - jquery-validate

I have password field(option) its not required to validate while submit form. But if i am entered data in the password field it must test the password strength custom validation. Please help me how to fix this issue. It validate only if password field is not empty.
My Code Here:
js.validator.addMethod("regx", function(value, element, regexpr) {
return regexpr.test(value);
}, "Password must contain one lower case letter,upper case letter,digit and special character ex:aaEs#s1#.");
js('#forms').validate({
rules: {
password:{
regx: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{5,20}$/
},
}
});

Add this.optional(element) to your conditional check to make this field optional.
js.validator.addMethod("regx", function(value, element, regexpr) {
return this.optional(element) || regexpr.test(value);
}, "Password must contain one lower case letter,upper case letter,digit and special character ex:aaEs#s1#.");

Related

Form level validation (no field level) with formik validation schema for combination of fields

Let's assume we have to use the form with username and nickname field. And the max count of each field is 250 letters and it is not mandatory required. But one of these fields should be exists.
The way it to add validation for each field by using Yup as below
const SignupSchema = Yup.object().shape({
userName: Yup.string()
.max(50, 'Too Long!')
.test('Required', 'one of these fields required', function(value){
return this.parent.nickName || value;
}),
nickName: Yup.string()
.max(50, 'Too Long!')
.test('Required', 'one of these fields required', function(value){
return this.parent.userName || value;
}),
});
But this is for field level validation, and I don't want to show error message for each field but show the "one of these items should be required" error message at the top or bottom of the whole form.
I am not sure how to get form level error message.

AutoForm 5.0.2 nested schema inputs required on update

I have schemas set up so that I can have an array of complex input sets. Something like:
address = {
street:{
type: String
},
city: {
type: String
},
active_address: {
type: Boolean,
optional: true
},
...
}
people: {
name:{
type: String
},
address:{
type: [address],
optional: true,
defaultValue: []
}
}
This way adding an address is optional, but if you add an address all of the address fields are required.
This worked in (I believe it was) version 4.2.2. This still works on insert type autoforms, but not on update type autoforms. Doing an update, none of the fields will submit unless all required fields in the nested schema are also valid.
For reference, I'm creating the form as such:
{{#autoForm collection="people" id=formId type="update" doc=getDocument autosave=true template="autoupdate"}}
{{> afQuickField name='name' template="autoupdate" placeholder="schemaLabel"}}
{{> afQuickField name='address' template="autoupdate"}}
{{/autoForm}}
My templates (autoupdate) I copy-pasted the entirety of bootstrap3 autoform templates and rearranged some of the html to fit my needs. I updated these to the best of my ability according to the 5.0.0 changelog when I updated. It could possibly be in there if someone can think of an attribute in the templates that would cause inconsistent behavior between insert and update that changed in 5.0.0.
More information
I just tried recreating all of my form templates using the bootstrap3 templates from 5.0.2. Still the same behavior.
+
I have a Boolean (checkbox) input in the address schema. Looking in a doc, the address array is populated with [0 : {active_address: false}]
active_address: {
type: Boolean,
optional: true
}
Not sure if that helps...
+
As per #mark's suggestion, I added defaultValue:[]. It fixed the issue... sort of. There are no "open" nested schemas in the update form now, and other values can be changed. If you "add" a nested schema to the form with the add button, that entire form becomes required even if you don't insert any value in any field. This happens regardless of the Boolean type input.
I can nail down the Boolean type input in the nested schema causes that entire nested schema to become necessary to do the insert. Removing the Boolean input caused it to be insertable again. So there's a new problem in the same vein.
This new issue can be found here
I think the best solution is to add a defaultValue: [] to the address field in the schema. The behavior you described in the question (not allowing the update) is actually intended -- read on to see why.
The thing is, this behavior only exists if an array form element has already been added to the form. What I mean is, if you click the minus sign that removes the street, city, etc. inputs from the form, the update succeeds because AutoForm doesn't misinterpret the unchecked checkbox as the user explicitly unchecking the box (and therefore setting the value to false). Setting the defaultValue to an empty array lets AutoForm know to not present the address form unless the user has explicitly clicked the plus sign (i.e, they have an address they want to enter), in which case the behavior of making the street, city, etc. fields required is what you want.
Note that this means you'll have to update the existing documents in your collection that are missing the address field and set it to an empty array. Something like this in the mongo shell:
db.people.update({ "address": { $exists: false } }, { $set: { "address": [] } }, { multi: true })
You'll probably want to make sure that the query is correct by running a find on the selector first.
Edit
If the behavior you want is to show the sub-form without making it required, you can work around the checkbox issue by using the formToDoc hook and filtering out all address objects that only have the active_address field set to false (the field that AutoForm mistakenly adds for us).
AutoForm.addHooks('yourFormId', {
formToDoc: function (doc) {
doc.address = _.reject(doc.address, function (a) {
return !a.street && !a.city && !a.active_address;
});
return doc;
}
});
The formToDoc hook is called every time the form is validated, so you can use it to modify the doc to make it so that AutoForm is never even aware that there is an address sub-field, unless a property of it has been set. Note that if you're using this solution you won't have to add the defaultValue: [] as stated above.

KendoUI DatePicker validation when multiple date fields are on a page

I'm looking to validate date fields on a page, which is simple (see this JSBin). BUT, when a page has multiple date fields on a page things start to get wacky...
See this JSBin and play around with invalid dates.
The invalid message doesn't know which input to bind to, causing error messages on the wrong inputs. Is there a way to trigger the correct input field?
Instead of defining a validator for the form, define a validator for each date as actually you want to validate the fields and not the form as a whole. You can do it as:
$(".datepicker").kendoDatePicker();
$(".datepicker").kendoValidator({
rules : {
//implement your custom date validation
dateValidation: function (e) {
console.log("e", e);
var currentDate = Date.parse($(e).val());
//Check if Date parse is successful
if (!currentDate) {
return false;
}
return true;
}
},
messages: {
//Define your custom validation massages
required : "Date is required message",
dateValidation: "Invalid date message"
}
});
Your JSBin modified here

Validation of dynamic fields in a MVC

My model looks like
public class Template
{
Id
Title
List<Field> Fields
}
The “Field” Entity contains information like Name, Caption, Type (TextBox/Select/Radio), Options, and validation rules (Range, Required, string length).
The standard validation in MVC is based on DataAnnotations, but I wants to validate (Both client and Server Side) the form dynamically based on Field Metadata which is dynamic and configurable.
Is it possible? Any pointers?
PS. I searched for the similar questions, but not able to find a solid answer.
I had a similar situation, this is how I handled it:
Server Side
When the POST happened I iterated over all the Fields values and did the Validation based on the validation rules I had on my objects. Then you can simply add ModelErrors to the Field object.
Since you push a Template object to the View you can access the Fields by name Fields[x].SomeProperty. Make sure you have a ValidationMessageFor for SomeProperty
ModelState.AddModelError("Fields[x].SomeProperty", "The Error Message you want to show.);
Client side
Make sure your form has an Id so you can access the Validate method().
Then you iterate over all the fields and just add the validation as you please.
For all the validations rules check the validation Jquery documentation.
$('#frmYourForm').validate();
for (var i = 0; i < 'CountOfAllFields'; i++)
{
$('#Fields_' + i + '__Foo').rules('add', { required: true, messages: { required: 'The Foo field is required'} });
$('#Fields_' + i + '__Bar').rules('add', { required: true, messages: { required: 'The Bar field is required'} });
}
I hope I helped you on your way !
Ps, use FireBug to help you find the correct names of the properties and that's how you can link them with the ModelErrors in the modelstate etc.

How to validate two or more mobile numbers in one field, when using jquery validation plugin?

I am using this to validate client forms. In one field i need to accept two or more country mobile number which should be a valid mobile number. Say if i need to accept Indian mobile number or US mobile number. How shall i validate both in one field?
Thanks.
You probably want to use the depends field.
$("#element").validate({
rules: {
phone: {
depends: function(element) {
if('behavestoA' || 'behavestoB'){ return true }else{ return false }
}
}
}
messages: {
phone: "Please format your phone number correctly"
}
})
in behavestoA or behavestoB you of course then have to put your conditions.
Good luck!

Resources