Reset validation for Paper Input? - javascript

I have a paper-input element like this:
<paper-input id="inputForValidation" required label="this input is manually validated" pattern="[a-zA-Z]*" error-message="letters only!"></paper-input>
<button onclick="validate()">Validate!</button>
When I validate the input and the validation fails it looks like this:
Without changing the input I want to programmatically reset the validation state such that it looks like before:
How can I reset the validation state to get the unvalidated view without changing the input?

Just set the invalid attribute of the paper-input element to false, e.g.
this.$.inputForValidation.invalid = false;

In your case you want the empty value is valid so you just have to remove the require attribute...
In more complicated case I think you want to do something like this :
Polymer({
is: "my-element",
validate: function(){
if(this.$.inputForValidation.value == ""){
//When the input is empty we want
this.$.inputForValidation.removeAttribute("required");
this.$.inputForValidation.validate();
this.$.inputForValidation.setAttribute("required", true);
}
}
});

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.

jQuery validator is validating against no longer existing form elements after ajax call

I have a form which dynamically adds or removes input fields depending on certain selections which have been made by the user.
The basic form looks like this, simplified:
<form action="...some/path..." id="MyForm" method="post">
<!-- the first input field is a select list, depending on the selected option, an ajax call will be made to update the div below with new input fields -->
<select name="selectList">
<option>#1</option>
<option>#2</option>
<option>#3</option>
<option>...</option>
</select>
<div id="UpdateThisSection"></div>
<input type="submit" value="Submit">
</form>
Depending on which option the user picks from the select list, the user will be presented with different input fields, which are rendered in the #UpdateThisSection div.
The input fields for option #1 would be:
Date Field (required), so the required attribute is set to the input field, as well as the custom data-type="Date" attribute
Text (optional), no required attribute is set
The input fields for option #2 would be:
Text (optional), no required attribute set
Text (optional), no required attribute set
The input fields for option #3 would be:
Text (optional), no required attribute set
Numeric (optional), required attribute set, as well as the custom data-type="Numeric" attribute
The jquery validation is implemented like this:
$("#MyForm").validate();
$.validator.addMethod("usDate",
function (value, element) {
return value.match(/^(0?[1-9]|1[0-2])[/., -](0?[1-9]|[12][0-9]|3[0-1])[/., -](19|20)?\d{2}$/);
},
"Please enter a valid date."
);
$("input[data-type='Date']").each(function () {
if ($(this).prop("required")) {
$(this).rules("add",
{
usDate: true
});
}
});
$("input[data-type='Numeric']").each(function () {
$(this).rules("add",
{
number: true
});
});
Validation works perfectly fine if I open the form and select any option. The form is being validated the way it should. However, if I change my mind and select a different option from the dropdown, the form is not validating correctly anymore. On submit, I see that the form is being validated with the previous form's requirements.
Looking at the $("#MyForm").validate() object on the console the invalid as well as the submitted property are still holding information of the previous form. What is the easiest way to reset the validator whenever a new ajax call load a new form element?
I tried to reset the form using $("#MyForm").validate().resetForm(); but it didn't clear the properties mentioned above.
Trying to clear the validation as suggested in this stackoverflow-post didn't resolve the issue for me either.
What is the easiest way to reset the validator whenever a new ajax call load a new form element?
In the Ajax success callback, remove all static rules from an element
$("#MyForm").rules( "remove" );
// Then add or re-add some static rules...
Sorry... can't easilly recreate that for a demo.

How to change hidden field to true when someone enter text in another field

I'm working with django templates... want to do something like this in JS:
If someone entered a text to textbox (id=super_text), I want to automatically change a boolean field hiddenInput (id=super_boolean) value to True.
I'm totally new in JS, was learning django backend for few months but I got my first project and one task is to do something like this in JS.
Can you help please? I will be thankfull (;
In HTML, <input>s can't be of type boolean, but the code below sets the text value of the hidden input to 'true'. (Even though I use the boolean value true, JS converts it to the string "true" when storing it in 'value', since the DOM knows that the input can only have a string as a value.)
<input type="text" id="super_text">
<input type="hidden" id="super_boolean">
<script>
document.getElementById('super_text').addEventListener('keypress', function(){
document.getElementById('super_boolean').value = true;
})
</script>

Retrieved unmasking value from inputmask masking value

I use input inputmask on my form input, this is code that make mask on my form
$('input[name="jumlah"]').inputmask("decimal", {
groupSeparator: ".",
autoGroup: true
});
then i need to get the value from the input with this way
var checkVal = $('input[name="jumlah"]').val();
i keep get mask value,
Ex:
on the input field when input number i can see 33.333 value on my field. then i need retrieved only 33333
how to get unmask value from input?
InputMask has a property that might help you: 'removeMaskOnSubmit'
Just set it as true and you should be good.
Something like this:
Inputmask.extendDefaults({
'removeMaskOnSubmit': true
});
found here (external link)

value-attribute seems not to show input-field-content

I'm trying to use jquery to check if every input-field has already been filled out. And if yes, I'd like to make a green border around the form.
This was my approach:
if($('input:text[value=""], textarea[value=""]').length == 0){
alert("DONE");
}
Hovever the value="" -Selector doesn't work.
It seems that the value-attribute only contains the input-field's default-value, but not the actual content inserted by the user - according to firebug.
This command alerts me the actual contents:
$('input:text[value!=""]').each(function(){
alert($(this).val());
});
My Question: Where are the actual input-field contents stored? And how can I use jQuery to check efficiently, if there are empty fields?
You are right, the attribute selectors only work with the value the attribute really has. Later on, changing the value of the input will only change the DOM element's internal state.
Where are the actual input-field contents stored?
You can access the value via the value property of the DOM element elementNode.value.
And how can I use jQuery to check efficiently, if there are empty fields?
You can use .filter:
$('input').filter(function() {
return !this.value;
});
A neat way of validating inputs is to attach a validation rule to the element for your script to find and validate against.
To make a field required:
<input type="text" data-validate="required" />
Your script:
$('[data-validate]').each(function() {
var rule = $(this).attr('data-validate'), value = $(this).val();
switch (rule) {
case 'required':
if (!value) {
alert('Field invalid!');
}
break;
}
});
It works pretty well for me.
You can make it more efficient by selecting only specific element types or children of a specific element (such as a form).
You could try using .filter() like this:
var empty = $('input:text').filter(function(){ return $(this).val() == "" }).length;
if(empty > 0){
alert("There are "+empty+" fields which have not been filled out");
}
my approach if you are not willing to use Jquery validate.
give a class to each of your input fields and then use Jquery class selector to test if those all have filled or not. You can use this even for dropdown too.
You should use this construction:
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
if (incomplete) {
alert('Please fill all fields!');
}
:input selector selects all input, textarea, select and button elements.
Read this: http://api.jquery.com/input-selector/

Categories

Resources