Assistance with a custom jquery validate error message function - jquery-validate

We have a rule that all of our validation messages must be in a summary, and thus the default "this field is required" doesn't cut it because the messages lose their context in a summary and therefore need specific field indicators.
I have a solution that I like rather well, but it soon became clear that there was a need for messages outside of just the required field (email, url, custom methods like phoneUS, etc), so I made some additions to my function.
I've been using jQuery for a while, but I'm not an expert in the optimization area, so I wanted to get some expert help on whether the function below could be optimized...my question is, "is there actually a better way to handle custom error messages in a summary?"
$('.required, .email').each(function(index) {
var $this = $(this);
var label = (
$this.is(':radio')
? $("label[data-name='"+$this.attr('name')+"']")
: label = $("label[for='"+$this.attr('id')+"']")
);
var customMessages = [{}];
if($this.hasClass('required')){
customMessages.required = "'" + label.text() + "' is required.";
}
if($this.hasClass('email')){
customMessages.email = "'" + label.text() + "' has an invalid email address.";
}
$this.rules("add", {
messages: customMessages
});
});
Here is the jsFiddle:
http://jsfiddle.net/GD5nw/1/

So why not just assign the custom message on a field-by-field basis for each field as is most typically done? It seems less verbose than what you've been doing.
http://docs.jquery.com/Plugins/Validation/validate#toptions
Example for input elements with name attribute assigned as first, second, and address.
$('#myform').validate({
rules: {
first: {
required: true
},
second: {
required: true
},
address: {
required: true,
digits: true // just an example
}
},
messages: {
first: {
required: "your first name is required"
},
second: {
required: "your last name is required"
},
address: {
required: "your address is required",
digits: "must only use digits on address"
}
}
});
Working Demo: http://jsfiddle.net/x4YBw/

Related

Yup validation with one field but two possible options (OR)

I am trying to create an input that takes a string that will be used as the href value for a tag. The href can be a url OR an email (for mailto:).
It works if I just check for email, or if I just check for URL. However, I want to check for one or the other. I am looking through yup documentation but I can't find a way to do an OR.
I noticed that there is a when to test for another field but I'm not checking if another field is true or not, or use test but I also can't seem to get it to work.
const vSchema = yup.object().shape({
text: yup.string().required(),
href: yup
.string()
.email('Link must be a URL or email')
.url('Link must be a URL or email')
.required('Link is a required field'),
});
test this
yup.addMethod(yup.string, "or", function(schemas, msg) {
return this.test({
name: "or",
message: "Please enter valid url or email." || msg,
test: value => {
if (Array.isArray(schemas) && schemas.length > 1) {
const resee = schemas.map(schema => schema.isValidSync(value));
return resee.some(res => res);
} else {
throw new TypeError("Schemas is not correct array schema");
}
},
exclusive: false
});
});

Semantic-ui form rule only if option is selected

I am using semantic ui and am trying to do some form validation with it.
The scenario I have is the user has 2 options: email,or phone app verrifcation. They select one of the options and enter whatever in a text field then click submit.
However I am not sure how to do rules on this with semantic UI.
I know if I wanted to check if it was blank I could do something like this:
$('.ui.form')
.form({
fields: {
CODE: {
identifier: 'code',
rules: [
{
type : 'empty',
prompt : 'Please enter your verification code'
}
]
}
} } );
However I would like additional rules based upon which option is selected. I have javascript that currently tells me the value of what is selected, and is updated on change. Unsure how to add it into the rules though, so that I can be like -- If phone was select, must be exactly 6 chars long, or IF email was selected, must be 18 chars long (different lengths for different option).
Is there a way to have conditional rules like this? Closet I could find was:
depends: 'id'
Which checks to ensure it is not empty.
Does anyone know how to have conditional rules such as this based on another form element? I am using the most recent version of Semantic-UI
You can do so by adding custom rules.
$.fn.form.settings.rules.atLeastOne = function (value, fields) {
fieldsToCompare = fields.split(",")
if (value) {
// current input is not empty
return true
} else {
// check the other input field(s)
// atLeastOne is not empty
atLeastOne = false
for (i = 0; i < fieldsToCompare.length; i++) {
// gets input based on id
if ($("#" + fieldsToCompare[i]).val()) {
atLeastOne = true
}
}
return atLeastOne
}
}
$(".ui.form").form({
fields: {
number:{
identifier: "number",
rules: [{
type: "exactLength[6]",
prompt: "number has to be 6 chars long"
}, {
// include the input fields to check atLeastOne[email, address, ...]
type: "atLeastOne[email]",
prompt: "Please provide an email or a number"
}]
},
email: {
identifier: "email",
rules: [{
type: "exactLength[18]",
prompt: "email has to be 18 chars long"
}, {
type: "atLeastOne[number]",
prompt: "Please provide an email or a number"
}]
}
}
});
Note that the function uses the input id as the identifier and not the input name. You might also want to look at optional fields.

Extjs validate in separate files

I'm trying to validate fields in my form, but I keep getting an error message.
Here is my code:
Ext.define('ExtDoc.views.extfields.FieldsValidator',{
valEng: function(val) {
var engTest = /^[a-zA-Z0-9\s]+$/;
Ext.apply(Ext.form.field.VTypes, {
eng: function(val, field) {
return engTest.test(val);
},
engText: 'Write it in English Please',
// vtype Mask property: The keystroke filter mask
engMask: /[a-zA-Z0-9_\u0600-\u06FF\s]/i
});
}
});
And I define my field as follow:
{
"name": "tik_moed_chasifa",
"type": "ExtDoc.views.extfields.ExtDocTextField",
"label": "moed_hasifa",
"vtype": "eng",
"msgTarget": "under"
}
The first snippet is in a separate js file, and I have it in my fields js file as required.
When I start typing text in the text field, I keep seeing the following error msg in the explorer debugger:
"SCRIPT438: Object doesn't support property or method 'eng' "
What could it be? Have I declared something wrong?
You have defined your own class with a function valEng(val), but you don't instantiate it, neither do you call the function anywhere.
Furthermore, your function valEng(val) does not require a parameter, because you are not using that parameter anywhere.
It would be far easier and more readable, would you remove the Ext.define part and create the validators right where you need them. For instance if you need them inside an initComponent function:
initComponent:function() {
var me = this;
Ext.apply(Ext.form.field.VTypes, {
mobileNumber:function(val, field) {
var numeric = /^[0-9]+$/
if(!Ext.String.startsWith(val,'+')) return false;
if(!numeric.test(val.substring(1))) return false;
return true;
},
mobileNumberText:'This is not a valid mobile number'
});
Ext.apply(me,{
....
items: [{
xtype:'fieldcontainer',
items:[{
xtype: 'combobox',
vtype: 'mobileNumber',
Or, you could add to your Application.js, in the init method, if you need it quite often at different levels of your application:
Ext.define('MyApp.Application', {
extend: 'Ext.app.Application',
views: [
],
controllers: [
],
stores: [
],
init:function() {
Ext.apply(Ext.form.field.VTypes, {
mobileNumber:function(val, field) {
var numeric = /^[0-9]+$/
if(!Ext.String.startsWith(val,'+')) return false;
if(!numeric.test(val.substring(1))) return false;
return true;
},
mobileNumberText:'This is not a valid mobile number'
});
}

JQGrid remove value from custom error message

In inline navigation, i want to remove user entered value from custom error message.
So far all examples have this sticked to message.
For e.g. I want to remove date "2013-blah blah"
(source: easycaptures.com)
Thanks.
You can use custom_func to achieve this.
Add editrules to column details in colModel like given below
editrules:{custom: true, custom_func: customValidationMessage}
and the function (In this case I am doing validation for required, you can do your validation for date in if condition )
function customValidationMessage(val, colname) {
if (val.trim() == "") {
return [ false,colname + " is required " ];
} else {
return [ true, "" ];
}
}

Credit card validation problem using multiple textbox

I'm using multiple textboxes for users to entry different credit cards#, with jquery validations. Ambiguously, only the first text box validation is working. Validation's are not working for the other boxes. There are no js errors too in error console.
It'll be very helpful if someone can please give me a clue.
//for first textbox
$("#cust_reg").validate({
rules: {
cc_num_local: {
required: true,
creditcard: true
}
}
});
//for second textbox
$("#cust_reg").validate({
rules: {
cc_num_roam: {
required: true,
creditcard: true
}
}
});
the relevant html only: http://pastie.textmate.org/2422338
You can have more then one HTML element using the id of cust_reg. If you do then only one will be available to your JavaScript code since one supersedes the other. It also isn't valid HTML. You'll need to change the name of the second field to be something different like cust_reg2.
Since you have one form and two different ID's you might try combining them in your code.
$("#cust_reg").validate({
rules: {
cc_num_local: {
required: true,
creditcard: true
},
cc_num_roam: {
required: true,
creditcard: true //Not sure if this can be the same name
}
}
});

Resources