jQuery Validate Plugin - Validate Hidden Field by Name - javascript

Primary Question
I'm new to the jQuery validate plugin. I need to validate hidden fields that are being added and removed dynamically and that share the same name. Example markup:
<input type="hidden" name="hdnItemID" value="123" />
<input type="hidden" name="hdnItemID" value="987" />
Basically, I need to know if any elements exist that have the name hdnItemID. If they exist, the validation should be successful, else, the validation should fail.
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
}
else {
//Form is invalid
}
I've looked at a few questions that seem close, but they don't seem to fit the bill. Any suggestions?
jQuery Validate Plugin - How to create a simple custom rule?
jquery validate - valid if hidden field has a value
Secondary Question
Assuming that what I'm asking is possible, how would I specify where the validation message is displayed? Currently, I'm placing an asterisk by each required element when the validation fails. I'd like to continue to do that, but place the validation message for the hidden fields by the submit button.

Use submitHandler event of the plugin to check if the hidden field exists or not. You can then conditionally submit the form. Try this.
$(function() {
$('#form1').validate({
submitHandler: function(form) {
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
form.submit();
}
else {
//Form is invalid
alert('form data invalid');
}
}
});
});

Related

How to display "Please fill out this field" for all empty and required fields in html form?

I have a form as shown in the fiddle https://jsfiddle.net/vrn7zx5h/3/ in which I want to show the warning sign "Please fill out this field" at the same time for all unfilled required fields.
I found the answer on SO (as shown below) but i am not sure how to integrate with the fiddle.
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
Problem Statement:
I am wondering what changes I should make in the fiddle so that the above pasted SO answer works with the fiddle.
Here is a JS fiddle that will show all error at one time. It is just barebone and not fancy. You'll need to make it fancy on your own. I also disabled the built-in validator as well with novalidate in the form tag.
https://jsfiddle.net/6kxc9hmq/1/
FYI: I also did not put in the functionality to hide the error message on next run, if the input now satisfies the condition.
Basically, I attached a submit event handler to the form and if the validator returned false, I told the form to not submit. Works only on IE9+ (I think) all the other browsers are usually fine with this method. The validator is basically just checking if the value of the input met the condition that I specified.
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
I think it should look like this, if I understand what you mean
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
In your form, add empty divs after each input element. And you can conditionally display messages in the div in your validation. E.g if(name ==‘ ‘){div.innerHTML = ‘please enter your name’}
The required Attribute
Add the required attribute to your form.
The required attribute tells the browser to only submit the form if the field in question is filled out. Obviously, this means that the field can’t be left empty, but it also means that, depending on other attributes or the field’s type, only certain types of values will be accepted.

HTML "required" attribute for multiple button with multiple text field on same form

I have HTML form which has multiple button and multiple text fields on same form some thing like below.
Form: #myform
TextField1 ---> Button1
TextField2 ---> Button2
.. so on like more number of fields
I want to apply "required" attribute only specific button to specific textfield (Button1 for TextField1 )
It will be grateful if someone provide solution in javascript by passing some parameter to perform this validation
According to mozilla "required" is not included. So "required" is not allowed on element "button". You can add, but it will not add validation. For button and i would use validation with javascript.
I found solution to suit my requirement which I asked in automated fashion, I am posting the code so that might be useful if someone searching solution like me
Calling function on button click
<input type="text" id="txtfield1" class="texttype0" th:field="*{txtfield1}" placeholder="Enter txtfield1">
<button type="submit" id="bt1" onclick="btn('txtfield1')" name="action" >Update</button>
And below is my javascript function
function btn(txtid) {
document.getElementById(txtid).setAttribute("required", true);
$('form#myform').find(
'input[type=text],input[type=date],select').each(
function() {
var name = $(this).attr('id');
if (txtid == name) {
$(name).prop("required", true);
} else {
$(name).prop("required", false);
document.getElementById(name).required = false;
}
});
}
This will search all element from a form and remove require attribute except the one which you passed in parameter.

Error handling for "required" keyword in html form submission

I am making a difficult design decision right now. I have a bunch of blanks in a form and two buttons in a html page, the two buttons are for "add" and "delete" data to/from a database (assuming that I have a method to retrieve data from the database and populate the form before deletion). I want to make a error handling mechanism such that
1) required fields must be filled before submission, and
2) empty form (hence record) cannot be deleted
The code I have is similar to the following:
<form id="fm" method="POST">
<input name="a" required>
<input name="b" required>
<!-- let's say I have 20 other blank fields -->
<button id="add"><input name="btn">Add</button>
<button id="delete"><input name="btn">Delete</button>
</form>
In my jquery, I have:
$("#fm").submit( function() {
return false;
});
$("#sbmbtn").click( function() {
$.post(............)
//and other magic tricks
});
If I were to put everything in .click function into the .submit function, javascript will automatically enforcing that "required" fields must be filled before submission. However, if i were to do this, the other button will behave oddly because both buttons are in the same form, and clicking on either one will trigger form submission, which is not desirable.
Long story short, I probably won't change the architecture much, what can I add or tweak to make sure the required fields are checked before submission?
required fields must be filled before submission, run this function before submission
function validate() {
var requiredFields = $('#fm input').filter('[required]');
var valid = true;
$.each(requiredFields, function(index, value){
if (value.value.length < 1) {
valid = false;
}
});
return valid;
}
and then use the return value from validate to make sure all fields are filled before running your submit function.
just disable the delete button if the form is empty
Edit: but all this will be useless if the user disables JavaScript so you have to have server side validation as well.

how to check if input field is empty on submit [duplicate]

This question already has answers here:
Check if inputs are empty using jQuery
(22 answers)
Closed 9 years ago.
I'm using jQuery so i wonder how can i show error message after i click submit button only if an input field is empty.
Below the code my simple form how to apply to it.
<form id="myid" name="myid" method="post" action="hook.php">
name : <input type="text" name="name" id="name">
age : <input type="text" name="age" id="age">
<input type="submit" id="submit" name="submit" value="Save" />
</form>
I would like to show error like this
As someone has already mentioned, you should probably look to use an external library for validation. That said, this seems like it might work (see JSFiddle):
var $form = $("#myid"),
$errorMsg = $("<span class='error'>This field is required..!!</span>");
$("#submit").on("click", function () {
// If any field is blank, we don't submit the form
var toReturn = true;
$("input", $form).each(function () {
// If our field is blank
if ($(this).val() == "") {
// Add an error message
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
// If the field is not blank
else {
// Remove the error message
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
You can use event.preventDefault to stop the default action happening. Then check your condition, display errors if the condition fails and submit the form if not.
$("#submit").click(function(event) {
event.preventDefault();
if($(this).val().length === 0) {
// display some error
} else {
$("#myid").submit();
}
});
Really I advice you to use some frameworks for form validation. Because that's the common task and it was already done 100000 times before. There are plenty of it, for example Parsley or Jquery plugin, but there are a lot of others which is simple and easily maintainable, just google 'javascript form validation'
Why is already implemented code better than custom in that case: 1) It already written, tested and working, 2) You almost never need only single validation, and really to validate form for several parameters could be a challenge and could lead to a big amount of validation code 3) framework is DRYer and a really a lot of other stuff.
I also advise you to use validation framework because you need more validation for different field. Use MooTools Floor this is most reliable framework for validation.
MooTool Floor
You can use the HTML5 required='required' option in the input tag...

How do I get KendoUI Validator to ignore hidden form elements?

I am attempting to use KendoUI Validator with an ASP.NET WebForms project.
I have a simple page, that has a number of inputs, and of course ASP.NET adds some hidden form elements as well.
I have the following questions:
Why does the KendoUI Validator not ignore hidden form fields, and how to I get it to?
Why does KendoUI apply the rules to every input field, and how to do get it to ignore some fields. I want a declarative way to do this, not by adding all sorts of exceptions in my validation rule, as per the example in the KendoUI Validator API page.
Shouldn't it be that if no rule is set as an attribute in the input element (eg; required) then no validation is applied?
Behavior I am getting:
With no validation specific attributes on the input element at all, the validation rules still get applied when I call .validate()
Hidden form elements are validated.
I am using the following kendo:
http://cdn.kendostatic.com/2013.2.716/js/jquery.min.js
http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js
http://cdn.kendostatic.com/2013.2.716/styles/kendo.common.min.css
http://cdn.kendostatic.com/2013.2.716/styles/kendo.default.min.css
I have put together a fiddle that demonstrates this:
http://jsfiddle.net/codeowl/B5ML4/3/
And here is the code, for those that don't have access to fiddle:
I have the following markup:
<form action="/" id="testForm">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="text" id="testInput" value="">
<a id="testValidate" href="javascript:;">Validate</a>
</form>
and the following script:
var validatable = $("#testForm").kendoValidator({
rules: {
testRule1: function (input) {
// Only "Tom" will be a valid value for the FirstName input
return input.is("[name=firstname]") && input.val() === "Tom";
},
testRule2: function (input) {
return $.trim(input.val()) !== "";
}
},
messages: {
testRule1: "Your name must be Test",
testRule2: "Your name must be Foo"
}
}).data("kendoValidator");
$("#testValidate").click(function () {
if (validatable.validate()) {
alert('passed');
}
});
and when I press the validate link it shows validation messages for the hidden fields.
For anyone interested, I did eventually get a response to this question. I had to post it on the KendoUI Premium Forums to get someone to respond.
Here is the response:
How do I get KendoUI Validator to ignore hidden form elements?
Indeed, the hidden input elements are passed through the validation
rules logic by default due to the fact that there are multiple widgets
which has a hidden input as part of there markup. However, as the
built-in rules relays on the presence of certain attributes, if there
are missing no validation will happen on the hidden inputs. Therefore,
your own custom rules should handle this scenario and skip the
appropriate elements. For example:
testRule2: function (input) {
if (!input.is(":hidden")) {
return $.trim(input.val()) !== "";
}
return true;
}
I'm writing this for new comers.
Simply make hidden inputs disabled
$('#hidden_input').prop('disabled', true) // won't check in kendo or standard jquery validation
$('#hidden_input').prop('disabled', false) // will check in kendo or standard jquery validation
validator._inputSelector=
":input:not(:button,[type=submit],[type=reset],[disabled],[readonly],[type=hidden],:hidden)
[data-validate!=false]
This will not validate hidden controls. Kendo 2018 version

Categories

Resources