Clear error message or reset validation using jQuery Validation plugin - jquery-plugins

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.

Related

parsley.js prevents submit after failing ajax validation has been corrected

i have a form where i need to see if an email address entered into the form is already in a database. this check needs to be performed conditionally based on the value of another field in the form.
here is the form field:
<input type="email" value="" class="form-control" name="email_bill" id="email" required data-parsley-type="email" data-parsley-registered="1" data-parsley-trigger="focusout submit">
and here's the validator code:
Parsley.addValidator('registered', {
validateString: function(value) {
if ($('input[name="d_type"]:checked').val() == 'S') {
return $.ajax({
type: "POST",
url: "/is_registered.html",
data: $('form').serialize()
});
} else {
var parent = $('#email').closest('div');
var this_id = $('#email').attr('data-parsley-id');
$(parent).removeClass('has-error').addClass('parsley-success');
$(this_id).remove();
return true;
}
},
messages: {en: "Someone has already registered with the Email address you entered"}
});
the server code is trivial and returns a '200 OK' header if the address isn't in the database and a '404 Not Found' if it is. that works.
i followed the example in the parsley.js custom validator example for the simple ajax request.
what happens is: if i enter a 'registered' address, i get the appropriate error message. if i then go and modify that address to one i know is NOT registered and tab or mouse out to the next field, the error message goes away, BUT the submit button doesn't work. to further complicate the situation, if i load and fill out a form with a 'non-registered' address, the submit button doesn't work either. it appears that execution of the custom validator disables submit upon entry.
i've played with this for hours, trying all sorts of event manipulation, but nothing works.
i should point out that if the checked value of d_type (see field definition above) is NOT 'S', then everything works as expected.
i am totally baffled as to why following the documentation results in failure.
as it turns out, this was not a problem with parsley at all.
a colleague created the form and the submit button had an id of "submit' which could not allow parsley to resolve the submit handler. under those circumstances, apparently parsley blocks the submit.
who knew?
well now, we know.....

MVC Custom Attribute - Client-side Validation - Warning: No message defined for 'field'

I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).
Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?
Below is my custom client validation script:
I included following scripts in EditProducts page.
Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).
FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.
Please advise!
I ran into this issue. I had created an MVC attribute called PasswordAttribute, with a client side validator called 'password'.
$.validator.addMethod('password', function (value, element, params) {
...[validation logic]
});
$.validator.unobtrusive.adapters.addBool('password');
As soon as I added this logic to the solution I got the error you saw on my Password and ConfirmPassword fields. Note that this occurred before the attribute was even used. Simply renaming the client side validator to 'passwordcheck' fixed the issue. I initially thought that the name 'password' possibly clashed with one of the pre-defined validators (cf. jQuery Validation Documentation) but this doesn't appear to be the case. I suspect now that it is a clash with the name or value for some input field attribute. Anyway, the solution was simply to rename the validator.
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html
$.validator.unobtrusive.adapters.add("requireif", function (options) {
$('#' + options.element.id).attr("data-msg", options.message);
// Add rule ...
});
You can change default warning message.
$.validator.addMethod("requireif", function (value, element, pair) {
// validate logic
return true/false;
}, "YOUR DEFAULT MESSAGE HERE");
Or
#Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })
Or if you can put it directly to your Html like this.
<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>

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.

jQuery Validate() addMethod forces "required:true"

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.

Resources