Handling default form values with jquery.validationEngine.js - javascript

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.

Related

Change input value using javascript in a form built with Aura

I have an input in a form built with aura (Salesforce JS framework):
<input class=" input uiInput uiInputText uiInput--default uiInput--input" type="text" aria-describedby="5284:0" placeholder="" id="7:4790;a" data-aura-rendered-by="17:4790;a" data-aura-class="uiInput uiInputText uiInput--default uiInput--input" data-interactive-lib-uid="54" aria-required="true">
I need to change the value of this input using javascript.
However, when doing:
document.getElementById("7:4790;a").value = "random value";
Visually, it changes the value in the input, but it is not taken into account when saving as if I didn't change anything.
How can I achieve this ?
Do I need to trigger a specific event so that aura takes notice of the new data ?
You need to create an attribute of string type.
<aura:attribute name="myInputValue" type="String" />
Pass the attribute to the value property of the input tag.
<input .... value="{! v.myInputValue}" />
Now, whenever you want to change the value in the input, you can simply do this from your javascript function:
component.set('v.myInputValue, "My new String" />
Important Note: Salesforce frameworks don't allow DOM level manipulation due to a security architecture called Locker service. It is not advisable to follow DOM level Manipulation. Instead, follow the state-based approach like above.

Validate Form Inputs on a good and reliable way

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.

Javascript if empty not working?

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

html5 oninvalid doesn't work after fixed the input field

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('')}
/>

Javascript Array in Class = How to make it valid

I am using this jQuery validation library on my website. It requires me to put the validation rules in the class part of the input tag. ie <input class="validate[required,custom[onlyLetter],length[0,100]]" name="firstname" type="text" />
Now this causes me to end up with code in mine that looks similar such as:
<input type="text"
id="charfname"
name="charfname"
value=""
style="width: 300px;"
class="validate[required,length[3,20],custom[noSpecialCaracters]]" />
Which as you see has a [ and ] in the class name. So when I run the page through a validator I get the error:
character "[" is not allowed in the value of attribute "class"
How do I fix this to make it valid but still have the library work?
Thanks
Use some other method for initialization or use another script? Use an alternate attribute and a custom DTD for example. Or throw away the attribute based init system and use something else. Either way you have to modify the plugin's code. You cannot use "[" and "]" characters in a class name and any other combination implying them, period.

Categories

Resources