jQuery 유효성 검사 오류 메시지를 지우는 방법?
클라이언트 측 유효성 검사를 위해 jQuery 유효성 검사 플러그인을 사용하고 있습니다. editUser()오류 메시지를 표시하는 '사용자 편집'버튼을 클릭하면 기능 이 호출됩니다.
그러나 'Clear'버튼을 클릭하면 별도의 함수를 호출하는 양식의 오류 메시지를 지우고 싶습니다 clearUser().
function clearUser() {
// Need to clear previous errors here
}
function editUser(){
var validator = $("#editUserForm").validate({
rules: {
userName: "required"
},
errorElement: "span",
messages: {
userName: errorMessages.E2
}
});
if(validator.form()){
// Form submission code
}
}
당신은 resetForm()방법을 원한다 :
var validator = $("#myform").validate(
...
...
);
$(".cancel").click(function() {
validator.resetForm();
});
나는 그들의 데모 중 하나의 출처에서 그것을 움켜 쥐었다 .
참고 :이 코드는 Bootstrap 3에서 작동하지 않습니다.
나는이 문제를 직접 만났다. 양식을 단계에 따라 구성하는 동안 양식의 일부를 조건부로 유효성 검증해야했습니다 (예 : 특정 입력이 런타임 중에 동적으로 추가됨). 결과적으로 선택 드롭 다운에 유효성 검사가 필요한 경우도 있고 그렇지 않은 경우도 있습니다. 그러나 시련이 끝날 무렵에는 검증이 필요했습니다. 결과적으로 해결 방법이 아닌 강력한 방법이 필요했습니다. 에 대한 소스 코드를 참조했습니다 jquery.validate.
다음은 내가 생각해 낸 것입니다.
코드에서 다음과 같이 보입니다.
function clearValidation(formElement){
//Internal $.validator is exposed through $(form).validate()
var validator = $(formElement).validate();
//Iterate through named elements inside of the form, and mark them as error free
$('[name]',formElement).each(function(){
validator.successList.push(this);//mark as error free
validator.showErrors();//remove error messages if present
});
validator.resetForm();//remove error class on name elements and clear history
validator.reset();//remove all error and success data
}
//used
var myForm = document.getElementById("myFormId");
clearValidation(myForm);
jQuery 확장으로 축소 :
$.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
//used:
$("#formId").clearValidation();
단순히 오류를 숨기려면 다음을 수행하십시오.
$("#clearButton").click(function() {
$("label.error").hide();
$(".error").removeClass("error");
});
If you specified the errorClass, call that class to hide instead error (the default) I used above.
If you didn't previously save the validators apart when attaching them to the form you can also just simply invoke
$("form").validate().resetForm();
as .validate() will return the same validators you attached previously (if you did so).
If you want to do it without using a separate variable then
$("#myForm").data('validator').resetForm();
Unfortunately, validator.resetForm() does NOT work, in many cases.
I have a case where, if someone hits the "Submit" on a form with blank values, it should ignore the "Submit." No errors. That's easy enough. If someone puts in a partial set of values, and hits "Submit," it should flag some of the fields with errors. If, however, they wipe out those values and hit "Submit" again, it should clear the errors. In this case, for some reason, there are no elements in the "currentElements" array within the validator, so executing .resetForm() does absolutely nothing.
There are bugs posted on this.
Until such time as they fix them, you need to use Nick Craver's answer, NOT Parrots' accepted answer.
You can use:
$("#myform").data('validator').resetForm();
If you want just clear validation labels you can use code from jquery.validate.js resetForm()
var validator = $('#Form').validate();
validator.submitted = {};
validator.prepareForm();
validator.hideErrors();
validator.elements().removeClass(validatorObject.settings.errorClass);
I think we just need to enter the inputs to clean everything
$("#your_div").click(function() {
$(".error").html('');
$(".error").removeClass("error");
});
For those using Bootstrap 3 code below will clean whole form: messages, icons and colors...
$('.form-group').each(function () { $(this).removeClass('has-success'); });
$('.form-group').each(function () { $(this).removeClass('has-error'); });
$('.form-group').each(function () { $(this).removeClass('has-feedback'); });
$('.help-block').each(function () { $(this).remove(); });
$('.form-control-feedback').each(function () { $(this).remove(); });
I tested with:
$("div.error").remove();
$(".error").removeClass("error");
It will be ok, when you need to validate it again.
var validator = $("#myForm").validate();
validator.destroy();
This will destroy all the validation errors
Tried every single answer. The only thing that worked for me was:
$("#editUserForm").get(0).reset();
Using:
jquery-validate/1.16.0
jquery-validation-unobtrusive/3.2.6/
None of the other solutions worked for me. resetForm() is clearly documented to reset the actual form, e.g. remove the data from the form, which is not what I want. It just happens to sometimes not do that, but just remove the errors. What finally worked for me is this:
validator.hideThese(validator.errors());
Try to use this for remove validation on the click on cancel
function HideValidators() {
var lblMsg = document.getElementById('<%= lblRFDChild.ClientID %>');
lblMsg.innerHTML = "";
if (window.Page_Validators) {
for (var vI = 0; vI < Page_Validators.length; vI++) {
var vValidator = Page_Validators[vI];
vValidator.isvalid = true;
ValidatorUpdateDisplay(vValidator);
}
}
}
Try to use:
onClick="$('.error').remove();"
on Clear button.
To remove the validation summary you could write this
$('div#errorMessage').remove();
However, once you removed , again if validation failed it won't show this validation summary because you removed it. Instead use hide and display using the below code
$('div#errorMessage').css('display', 'none');
$('div#errorMessage').css('display', 'block');
None of the above solutions worked for me. I was disappointed at wasting my time on them. However there is an easy solution.
The solution was achieved by comparing the HTML mark up for the valid state and HTML mark up for the error state.
No errors would produce:
<div class="validation-summary-valid" data-valmsg-summary="true"></div>
when an error occurs this div is populated with the errors and the class is changed to validation-summary-errors:
<div class="validation-summary-errors" data-valmsg-summary="true">
The solution is very simple. Clear the HTML of the div which contains the errors and then change the class back to the valid state.
$('.validation-summary-errors').html()
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-valid').removeClass('validation-summary-errors');
Happy coding.
If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.
this.invalid = {};
I just did
$('.input-validation-error').removeClass('input-validation-error');
to remove red border on the input error fields.
$(FORM_ID).validate().resetForm(); is still not working as expected.
I am clearing form with resetForm(). It works in all case except one!!
When I load any form via Ajax and apply form validation after loading my dynamic HTML, then after when I try to reset the form with resetForm() and it fails and also it flushed off all validation I am applying on form elements.
So kindly do not use this for Ajax loaded forms OR manually initialized validation.
P.S. You need to use Nick Craver's answer for such scenario as I explained.
In my case helped with approach:
$(".field-validation-error span").hide();
If you want to hide a validation in client side that is not part of a form submit you can use the following code:
$(this).closest("div").find(".field-validation-error").empty();
$(this).removeClass("input-validation-error");
validator.resetForm() method clear error text. But if you want to remove the RED border from fields you have to remove the class has-error
$('#[FORM_ID] .form-group').removeClass('has-error');
Function using the approaches of Travis J, JLewkovich and Nick Craver...
// NOTE: Clears residual validation errors from the library "jquery.validate.js".
// By Travis J and Questor
// [Ref.: https://stackoverflow.com/a/16025232/3223785 ]
function clearJqValidErrors(formElement) {
// NOTE: Internal "$.validator" is exposed through "$(form).validate()". By Travis J
var validator = $(formElement).validate();
// NOTE: Iterate through named elements inside of the form, and mark them as
// error free. By Travis J
$(":input", formElement).each(function () {
// NOTE: Get all form elements (input, textarea and select) using JQuery. By Questor
// [Refs.: https://stackoverflow.com/a/12862623/3223785 ,
// https://api.jquery.com/input-selector/ ]
validator.successList.push(this); // mark as error free
validator.showErrors(); // remove error messages if present
});
validator.resetForm(); // remove error class on name elements and clear history
validator.reset(); // remove all error and success data
// NOTE: For those using bootstrap, there are cases where resetForm() does not
// clear all the instances of ".error" on the child elements of the form. This
// will leave residual CSS like red text color unless you call ".removeClass()".
// By JLewkovich and Nick Craver
// [Ref.: https://stackoverflow.com/a/2086348/3223785 ,
// https://stackoverflow.com/a/2086363/3223785 ]
$(formElement).find("label.error").hide();
$(formElement).find(".error").removeClass("error");
}
clearJqValidErrors($("#some_form_id"));
참고URL : https://stackoverflow.com/questions/2086287/how-to-clear-jquery-validation-error-messages
'Programming' 카테고리의 다른 글
| Sublime Text 3에서 줄을 주석 처리하는 키보드 단축키 (0) | 2020.06.02 |
|---|---|
| 머티리얼 디자인 스타일링 경고 대화 상자 (0) | 2020.06.02 |
| 인쇄 가능한 Twitter-Bootstrap 페이지를 만드는 방법 (0) | 2020.06.02 |
| WebStorm에서 기존 파일의 파일 형식 연결을 어떻게 변경합니까? (0) | 2020.06.02 |
| jQuery를 사용하여 드롭 다운의 선택된 인덱스 설정 (0) | 2020.06.02 |