I have this input code in my form:
<input maxlength="255" id="information_name" name="information[name]" oninvalid="check(this)" placeholder="Nombre Completo" required="required" size="30" style="width:528px;height:25px;" tabindex="3" type="text">
I change the oninvalid message with this javascritp code:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('Debe corregir este campo.');
}
}
</script>
Here is the problem, if I clicked on submit and the field is empty, the field shome the error so I need to fill the field, but after fill the field, I still getting the warning even the fill is not empty.
What I'm doing wrong???
If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to take effects of your new input you have to clear the custom validity.
Simply you can use the following:
<input required maxlength="255" id="information_name" minlength=1 name="information[name]" oninvalid="setCustomValidity('Should not be left empty.')"
oninput="setCustomValidity('')" />
There is no need to use Javascript for this.
You can set a custom validity message with setCustomValidity, however any non-blank string will cause the field to act as if it had an invalid value. You need to setCustomValidity('') to clear the invalidated state of the field.
If your validity is simple and controlled via field attributes, you can use object.willValidate to do the test and set the custom validity message:
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')"
If you setCustomValidity to any value that is not the empty string then that will cause the input to be in the invalid state. So your condition is checking for a value, then setting the field to be invalid either way. Only setCustomValidity when the value in the field is actually invalid, otherwise set it to an empty string:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('');
}
}
</script>
For me only oninvalid="this.setCustomValidity(this.willValidate ? '' :'You must choose the account type from the list')" works. There are lots of issues while using it with IE.
The issue is that the custom validity error message needs to be reset to blank/empty again, or the field will never validate (even with correct data).
I use oninvalid to set the custom validity error message, and then use onchange to set the message back to default (blank/empty), and then when the form is checked again it will correctly submit if data was corrected, or it will set the custom error message again if there is problem.
So something like this:
<input type="number" oninvalid="this.setCustomValidity('You need to enter an INTEGER in this field')" onchange="this.setCustomValidity('')" name="int-only" value="0" min="0" step="1">
for React Hooks Typescript users
const inputRef = useRef<HTMLInputElement>(null);
function setCustomValidity(customMsg?: string) {
inputRef.current?.setCustomValidity(
typeof customMsg === 'string' ? '' : t.errors.requiredField,
);
}
<input
ref={inputRef}
onInvalid={() => setCustomValidity()}
onInput={() => setCustomValidity('')}
/>
Related
In many forms I am developing with jQuery validation plugin I have many fields to fill like the following:
<p>
<label>Nome</label>
<span class="field">
<input type="text" name="nome" id="nome" class="smallinput"" value=""/>
</span>
</p>
and these fields are declared as required and if they are empty a message error is correctly shown. After that I would like the error message to hide when the user enters information. However, this does not happen. How can I set this? Moreover I have some fields which should contain email addresses whose rule is
email:{
required: true,
email: true,
},
and it happens that some email addresses are claimed to be not valid while instead they are. Is there a way to fix this?
SOLUTION
For those who might be interested, what I have tried is to add a class "req" to span elements which are required and when the user types in something and the value changes and is different from the void string, then an attribute style is added to generated label error, like that:
jQuery(".req").on('input',function(){
if (this.value != "")
jQuery(this).find("label").attr('style','display:none !important');
});
This seems to work fine. Obviously, if the value becomes again void then the red label error message is shown again.
On my page im working on, are a lot of input-forms.
I want to check the user inputs before submit.
Example
HTML/PHP
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
and actually im doing the following in Javascript
Javascript
function dataValidation() {
error=false;
var adress = document.getElementById('adress').value;
var amount = document.getElementById('adress').value;
if (adress == ""){
error=true;
}
if (amount >0 && amount < 999){
}
else {
error=true;
}
if (error == false){
document.forms["myForm"].submit();
}
}
So, basically this works fine for my, but the problem is, i have to create that function for every form, and add a IF for every field
So, im looking for a better solution
Idea 1 : Add a list, wich provides the types of input, like
adress = not empty,
amount = >0 && <999,
and then create a function, which checks all fields with that list
Idea 2: Add a tag or something directly to the input field, what it should contain. and then create a function which checks all the fields
Does somebody have a Idea how this can be done, and would like to help/advise me?
you could try this by jquery as:
your html:
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
<input type="button" id="check_input">
and apply jquery for all input field
$("#check_input").click(function() {
$("input").each(function() {
var element = $(this);
if(element.val() == "") {
element.css("border","1px solid red");
element.attr("placeholder","Field is empty");
return false;
}
});
});
if you have multiple forms with same fields try to call validation externally it will reduce some of your work apart from that i dont know any other method so lets wait for others reply
You might wanna consider using HTML5.
HTML5 can save time writing JS validations. For example to validate an email address you could use the following:
<input type="email" name="email" required />
Notice the type="email" and required. Instead of using js for validating, you could use HTML5 form attributes with Regular Expression Patterns.
For example If I want to create an input field which accepts only one numbers and 3 uppercase letters, I can easily do with it using a RegEx pattern:
<input type="text" pattern="[0-9][A-Z]{3}">
Read a little bit more on HTML5 and RegEx. It could help you.
So I'm trying to change the color of a submit button if the form is empty. So I'm not really sure what I'm doing wrong, since I'm super new, but here's the code I have at the moment.
My partial form
<div class="field">
<input type="email" placeholder="Email">
</div>
<div class="submit">
<input type="submit" value="Reset Password">
</div>
And the JS
if ($('#field'.is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}
Any ideas?
You specified id's in your jQuery when it should be classes -
if ($('.field'.is(':empty'))){ // field is a class, not an id, extra parentheses needed
$("#submit").css({"backgroundColor":"black"});
}
BUT, what you should be doing is checking the value of the email field, because the input makes the field "not empty" which means that the above WILL NEVER WORK
What you need to do is check whether the value of the input has any length, the input's container is not relevant:
if(!$('input[name="email"]').val().length) {
$('#submit').css({"backgroundColor":"black"});
}
EDIT: Finalized code after the OP made his desires clearer (validating e-mail) -
$('input[name="email"]').change(function () {
// regex to validate e-mail address
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var validEmail = regex.test( $(this).val() );
if(true == validEmail) {
$('#submit').css({
"background": "#CCCCCC",
"color": "black"
});
}
});
field is a class and you have a syntax error in there. Closing parenthesis after 'field' is missing
Try:
if ($('.field').is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}
Class start with a dot (.)
I'd start with hash #
That is your error
if ($('#field').is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}
You have to close the paren on '#field' so that you get a jquery object back to run the is function on.
Also your 'field' is a class not an id so you need a . not a # selector.
All this of course also depends on you moving the class field to the input, since you don't actually want to check for empty on a div.
So you actually want to do this with your whole code:
<div>
<input class="field" type="email" placeholder="Email">
</div>
<div>
<input class="submit" type="submit" value="Reset Password">
</div>
if ($('.field').is(':empty')){
$(".submit").css({"backgroundColor":"black"});
}
You've got some syntax errors in your code that are keeping it from executing properly:
You are querying the DOM object with an id of field, when you actually assigned your div a class of field. Change your query to $('.field') and it should work.
You neglected to close the parens on your call to the jQuery function $, this will prevent it from properly returning a jQuery object on which to call the is() method.
You are using the jQuery :empty pseudoselector to check if your div has any value entered, but this is not the intended use of this function. Rather, you should use the val() method directly on the input itself to check if the input has had anything entered into itself, and use that as your conditional.
You are querying your submit button with an id of #submit, but your submit input has not been assigned any id. You can either assign it an id of #submit or query it by its type attribute.
With these errors corrected, your code should look like this:
if (!$('.field > input').val()){
$("input[type='submit']").css("backgroundColor", "black");
}
You can check out the working code here
I am using jquery.validationEngine.js for form validation .
I was downloaded this js from http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
this site.But it not works for checking validation for default value such as I have first name field whose value is "First Name".I want validation for checking that this field should not be blank but it not works because it contains default value "First Name".
Also I want this should work in jquery.validationEngine.js file because I have to many validations on form & I am using this js.
My field is
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
If anyone using this file let me know & help to solve this problem.
If you wish to use validationEngine to validate your form the way you describe, there appear to be at least three solutions based on the documentation.
1) You can create a new custom regex in the translation file for each default text value, and then add that custom regex to the relevant form item. This is probably the trickiest of your options, as you will need to use a negative lookahead or something similar to get the regex correct.
2) Have the validator call one or more functions that you write to handle your special cases. I don't know if validationEngine allows you to pass parameters to the function--the documentation says nothing about that--so I'd guess it doesn't. This may mean that you will need to either write a separate function for each default value or else use a global variable to indicate the default value you are checking for. A function for your Uname field in your code snippet might look like this:
function checkUname(field, rules, i, options){
if (field.val() == "User Name") {
return "You must type in your username.";
}
Once that function is defined, you can use something like this to use it:
<input type="text" class="form validate[required,funcCall[checkUname]]" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
3) You can write a single JavaScript function that goes through each field in your form and, if it finds the default value, changes it to an empty string. Then attach that function to the onsubmit event in your form. This may be the easiest option, but it depends on your function running before the validationEngine code. If that's not the case, then it won't work.
Here is a good example
How do you validate optional fields with default value?
Otherwise see the question I posted as identical question with the possible change
jQuery.validator.addMethod("defaultInvalid", function(value, element) {
if (element.value == element.defaultValue) return false;
}
instead of the switch/case
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value==this.defaultValue) this.value=''"
onblur="if(this.value=='') this.value=this.defaultValue" />
You should set the placeholder value using the HTML5 placeholder attribute instead of JavaScript.
I am using the jQuery date picker calendar in a form. Once submitted the form passes params along via the url to a third party site. Everything works fine, except for one thing.
If the value inserted into the date field by the datepicker calendar is subsequently deleted, or if the default date, that is in the form on page load, is deleted and the form is submitted I get the following error:
"Conversion from string "" to type 'Date' is not valid."
The solution to my problem is really simple, I want to validate the text field where the date is submitted and send out a default date (current date) if the field is empty for any reason. The problem is I am terrible at Javascript and cannot figure out how to do this.
Here is the form code for my date field.
[var('default_date' = date)]
<input type="text" id="datepicker" name="txtdate" value="[$default_date]" onfocus="if (this.value == '[$default_date]') this.value = '';" onchange="form.BeginDate.value = this.value; form.EndDate.value = this.value;" />
<input type="hidden" name="BeginDate" value="[$default_date]"/>
<input type="hidden" name="EndDate" value="[$default_date]"/>
This is really old and probably solved, but what the heck.
Simplest way to do this is to add a little more javascript to the input's onchange event.
onchange="if( this.value.length > 0 ) { form.BeginDate.value = form.EndDate.value = this.value; } else { form.BeginDate.value = form.EndDate.value = '[$default_date]'; } " />
of course their are still all sorts of other problems associated with date validation, but this is a straightforward way to check for a blank value and return a default based on your current code structure.