jQuery Validate() addMethod forces "required:true" - jquery-validate

So i got a form with the jQuery validate() plugin. I added a custom method to check if the CNPJ (id number for companies in Brazil) is valid or not. The field is not required, i just wish to check its value if someone's writting something. The problem is that when adding this rule:
rules: {
cnpjcampo: {cnpjvalidate: true}
}
It does make it "required".
I've tryed this:
rules: {
cnpjcampo: {required:false, cnpjvalidate: true}
}
Does not affect anything.
My form is using the jQuery wizard form as well as chosen and the [Form plugin].
To get a clear view of what i'm doing, i've set up a jsFiddle. I you hit the Next button (Proximo) it'll trigger the validate plugin and tell you that the name (nome fantasia) is wrong, which is correct as set to "required" and also the CNPJ, which should not.

Found a solution. I erased the addMethod i was using, replaced it with another js file found here and changed the rules to this:
validationOptions: {
rules: {
"cpfsocio1" : { cpf: 'valid' /* 'valid' : sem formatação; 'format' : só formato; 'both' : os 2 */ },
"cpfsocio2" : { cpf: 'valid' },
"cnpjcampo" : { cnpj: 'valid' }
}
},
Here's the JsFiddle updated for those interested.

Related

redux-form only show validation errors on submit

Is there a way to configure redux-form so that validation errors only show when the form is submitted?
Also I would like to clear an individual form field error when a user starts typing or makes a change.
Is this possible with redux-form?
You're responsible for rendering any validation errors, so you can configure them only to be visible after submission has failed (i.e. the user pressed submit and your validations came back as failing). For this, your input components wrapped with Field are passed a meta object as a prop that contains a submitFailed field that tells whether form submission has failed. The actual code for rendering that component could look something like this:
render() {
const { meta: { error, submitFailed } } = this.props
return (
// ... rendering the input and then some
{ error && submitFailed ? (
<span className="validation-error">{ error }</span>
) : null }
// ... rendering the rest
)
}
For not showing errors while the user is typing, you're responsible for enabling that behavior and the props passed to your wrapped input component hold the keys, this time the meta object holds a field called active, which tells you whether this input has focus or not. Code could be something like this (building on the previous example):
render() {
const { meta: { active, error, submitFailed } } = this.props
return (
// ... rendering the input and then some
{ !active && (error && submitFailed) ? (
<span className="validation-error">{ error }</span>
) : null }
// ... rendering the rest
)
}
Hope this helps!
I'm also had this problem, the reason was using touchOnChange flag
reduxForm({
form: 'MyForm',
enableReinitialize: true,
touchOnChange: true,
})
So I removed this flag from reduxForm options and the code started working correctly - I saw the validation errors on submit only
reduxForm({
form: 'MyForm',
enableReinitialize: true,
})
Example from official site
https://redux-form.com/8.2.2/examples/fieldlevelvalidation/

jQuery Validation show input name in error message

So I have this:
<input name="fname" id="fname" data-message-name="First Name" />
I'm running .validate() on this form and I have all the error placements correct, but I want ALL the messages (being dynamic.. not having to type them statically) to show the attribute data-message-name in the error message instead of saying 'this'.
Right now, I have this:
$('.validate-form').validate({
wrapper: "li",
errorPlacement: function(error, element) {
error.appendTo( $(element.parents('form').attr('data-error-container')) );
}
});
It spits out this error:
This field is required.
I want it to say:
First Name field is required.
I looked over the documentation and I can't seem to find where it goes into detail for this. I'm using this plugin to be exact: http://jqueryvalidation.org/documentation/
Thanks for any help.
If you're searching the docs for this, you won't find it because it's not a feature of this plugin.
However, you can use element.attr('data-message-name') to get the text from your attribute and incorporate it into your message. I tried making a demo but it was unreliable and overly complex. (The reason has to do with how/when the errorPlacement callback function is called. Once the message is placed within the layout, the callback is not fired again but the message is simply toggled.)
Your best solution is the simplest. Just use the custom messages option as it was designed....
$('.validate-form').validate({
rules: {
fname: {
required: true
}
},
messages: {
fname: {
required: "First Name is required"
}
},
....
});

AngularJS: Is there any way to determine which fields are making a form invalid?

I have the following code in an AngularJS application, inside of a controller,
which is called from an ng-submit function, which belongs to a form with name profileForm:
$scope.updateProfile = function() {
if($scope.profileForm.$invalid) {
//error handling..
}
//etc.
};
Inside of this function, is there any way to figure out which fields are causing the entire form to be called invalid?
Each input name's validation information is exposed as property in form's name in scope.
HTML
<form name="someForm" action="/">
<input name="username" required />
<input name="password" type="password" required />
</form>
JS
$scope.someForm.username.$valid
// > false
$scope.someForm.password.$error
// > { required: true }
The exposed properties are $pristine, $dirty, $valid, $invalid, $error.
If you want to iterate over the errors for some reason:
$scope.someForm.$error
// > { required: [{$name: "username", $error: true /*...*/},
// {$name: "password", /*..*/}] }
Each rule in error will be exposed in $error.
Here is a plunkr to play with http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview
For checking which field of form is invalid
console.log($scope.FORM_NAME.$error.required);
this will output the array of invalid fields of the form
If you want to see which fields are messing up with your validation and you have jQuery to help you, just search for the "ng-invalid" class on the javascript console.
$('.ng-invalid');
It will list all DOM elements which failed validation for any reason.
You can loop through form.$error.pattern.
$scope.updateProfile = function() {
var error = $scope.profileForm.$error;
angular.forEach(error.pattern, function(field){
if(field.$invalid){
var fieldName = field.$name;
....
}
});
}
I wanted to display all the errors in the disabled Save button tooltip, so the user will know why is disable instead of scrolling up and down the long form.
Note: remember to add name property to the fields in your form
if (frm) {
disable = frm.$invalid;
if (frm.$invalid && frm.$error && frm.$error.required) {
frm.$error.required.forEach(function (error) {
disableArray.push(error.$name + ' is required');
});
}
}
if (disableArray.length > 0) {
vm.disableMessage = disableArray.toString();
}
For my application i display error like this:
<ul ng-repeat="errs in myForm.$error">
<li ng-repeat="err in errs">{{err.$name}}</li></ul>
if you want to see everything, just user 'err' that will display something like this:
"$validators": {},
"$asyncValidators": {},
"$parsers": [],
"$formatters": [],
"$viewChangeListeners": [],
"$untouched": true,
"$touched": false,
"$pristine": true,
"$dirty": false,
"$valid": false,
"$invalid": true,
"$error": { "required": true },
"$name": "errorfieldName",
"$options": {}
Not this well formatted, but you will see these things there...
When any field is invalid, if you try to get its value, it will be undefined.
Lets say you have a text input attached to $scope.mynum that is valid only when you type numbers, and you have typed ABC on it.
If you try to get the value of $scope.mynum, it would be undefined; it wouldn't return the ABC.
(Probably you know all this, but anyway)
So, I would use an array that have all the elements that need validation that I have added to the scope and use a filter (with underscore.js for example) to check which ones return as typeof undefined.
And those would be the fields causing the invalid state.
If you want to find field(s) which invalidates form on UI without programmatically, just right click inspect (open developer tools in elements view) then search for ng-invalid with ctrl+f inside this tab. Then for each field you find ng-invalid class for, you can check if field is not given any value while it is required, or other rules it may violate (invalid email format, out of range / max / min definition, etc.). This is the easiest way.

How to add a custom validation to Magento prototype

I want to make a simple url validator for some custom fields. I tried the default ones (adding the class validate-url or validate-clean-url to the input) - but these don't work quite as I would like them to, so I want to write some of my own javascript, but integrated with the prototype validation.
Does anyone have any ideas how I can do this?
I didn't find anything helpful in my searches, and I am not very Prototype-savy (worked mostly with jQuery).
You can create your own custom validation function using
<script type="text/javascript">
var theForm = new VarienForm('theForm', true);
Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
if(the_field_value == 'baz')
{
return true;
}
return false;
});
</script>
See http://magento-quickies.tumblr.com/post/6579512188/magento-custom-form-validation
or
if(Validation) {
Validation.addAllThese([
[
'validation-myown',
'Please insert proper word',
function(v,r){ return v.indexOf('valid')==-1?false:true }
],
[ ]
])
}
see http://blog.baobaz.com/en/blog/custom-javascript-form-validators
In /js/prototype/validation.js (or the files for this kind of thing you have). You have a section with an array of :
classname :message on fail : function(v){your check return true/false;} to check if v is valid or not
This section is around line 420.
You can add your validation to this array or modify validate-url here is what it looks like :
['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
v = (v || '').replace(/^\s+/, '').replace(/\s+$/, '');
return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?(.*)?$/i.test(v)
}],
Edit : R.S answered maybe better by showing how to do without changing the js file. More convenient ;)

Clear error message or reset validation using jQuery Validation plugin

I am a newbie to jQuery and I aplogize if this question is very basic.
I am using bassistance's Valiation plugin to validate a simple form. One of the text fields is mandatory - so I set required flag under rules and a corresponding message under messages. The problem I have is, once the validation kicks in, the error message I've set is displayed even if the field is blank (meaning, if the user deletes the contents of the field to start from scratch). Is there anyway to clear the error message or reset the validation if the field becomes empty? I tried to use the resetForm(), but looks like I can't use it while it's still validating. Here's part of the code:
$(document).ready(function() {
var validator = $("#form1").validate({
rules: {
fname: {
required: true,
remote: 'http://localhost/check_name.php'
}
},
messages: {
fname: {
required: "Enter a valid jobname. eg: 99999_Disney",
remote: "Name already exists";
}
}
});
Thanks for your help!
I solved the problem. Not sure if it's the most elegant way to do it, but it works. I had to clear the invalid state of the field somehow. I tried resetForm() but that didn't work. In the end I used something like this:
if ($("#ID").val()=="") {
validator.resetForm();
$("#ID").rules("remove", "required minlength");
}
and as needed added those rules back to the ID using:
$("#ID").rules("add", {
required: true,
minlength: 5,
messages: {//messages
},
});
You could try using a validation method, like so:
jQuery.validator.addMethod("ValReqJobName", valReqJobName, "Enter a valid jobname.");
And then, in the rules object, under "fname", just add "ValReqJobName: true".
Within the "valReqJobName" function you can allow for the field to be blank, or add whatever custom logic you want.

Resources