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.
Related
I have a loop of html forms <input type="number">, which are basically simple algebra calculations for certain people to fill in. I set the correct answer by limiting both the max and min accepted number to the same number. However, in this way, if the participant gives a wrong answer, the reject message would be something like this: "values must be greater than or equal to ...". It is technically correct but I would like it to only say "incorrect answer, please try again".
Is there any way to do this?
Tried to use something like alert =, but it doesn't meet my requirements.
There's ${parameters.numbers} and ${parameters.answers} in the code because I am using lab.js for the looping. They just mean every time the number in the equation and the answer would change. For example, for the first loop ${parameters.numbers} is 200, and the corresponding answer ${parameters.answers} is 194. lab.js would take care of converting these two parameters to actual numbers for each loop of the form.
<form>
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="${parameters.answers}" min="${parameters.answers}"><br>
<button type="submit">OK</button>
</form>
I try to avoid a dramatic alert dialogue for this, just a non-intrusive message like the default style would be good. If you want to recreate the default "values must be greater than or equal to ..." message, just replace the parameters like this would be good:
<form>
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="194" min="194"><br>
<button type="submit">OK</button>
</form>
I agree with #ElroyJetson that putting the answer inside the tag is not a good idea, but I focused this answer on the way you can set and unset the error message.
I used jQuery, but this can also be done with plain javascript.
The idea is to group the input tag with a span tag (here inside the div with class input-field).
When the value changes or when the form is submitted (in this case when the value changes), you remove any previous error message from the span tag, and then perform the validation. If there is an error you set it in the span tag.
In this way the error message will show below the input element.
To try it fill in an answer and click outside of the input box.
$(document).ready(function(){
$(".input-field").change(function(){
let $inputField = $(this);
let $input = $inputField.find("input");
let $errorMsg = $inputField.find("span.err-msg");
let max = Number($input.data("max"));
let min = Number($input.data("min"));
$errorMsg.text("");
let v = Number($input.val());
if(v < min || v > max){
$errorMsg.text("Invalid answer");
}
});
});
.err-msg{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-field">
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" data-max="194" data-min="194"><br>
<span class="err-msg"></span>
</div>
</form>
Don't set the correct answer with min & max. Instead, just call a javascript function by giving your button tag an onClick to evaluate if the user's answer is correct.
<button onclick="evaluateAnswer('.algebra');" class="submitBtn" >OK</button>
Then your javascript should look something like this:
function evaluateAnswer(cssClass){
var usersAnswer = $(cssClass).val();
var actualCorrectAnswer = 100;
if(usersAnswer == actualCorrectAnswer){
//Do something to proceed
}else{
alert('Sorry, your answer is incorrect');
}
}
Also, I just noticed that you did not want to alert as-in a javascript alert. What you could do is style your message and give it a css class that has the property display:none. Then when you want to show the message when user enters the wrong answer, you can use javascript to remove the class, and also use javascript to add the class back when user enters correct answer.
Edit
You should maybe store your correct answers in a database, evaluate it's correctness serverside, and use Ajax to display the message to prevent users from being able to right-click -> view source and look at the answers in your client-side code
My current solution is like this. There is invisible html elements which stores the correct answer, and the js script validates if the input is correct. Again, the ${} parts represents variables that change in each loop.
html part
<main class="content-horizontal-center content-vertical-center">
<form name="mathEvaluation">
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="answer" type="number" id="answer" required="" size="3"><br>
<button type="submit">OK</button>
<input type="hidden" id="hidenAnswer" value=${parameters.answers} />
</form>
</main>
js part
this.options.validator = function(data) {
if(mathEvaluation.answer.value == mathEvaluation.hidenAnswer.value){
return true
} else {
alert("Please enter the correct number.")
}
}
I've been doing a lot of research on this and still can't find a good solution. Basically, I have this field in my form that should ONLY allow numbers. However, I'm able to enter mac special characters inside that field by doing:
Hold down option + shift and then pressing any button from keyboard (example: h j k l u i , etc).
Please see attached picture.
Can anyone help me on NOT allowing such characters inside the ID field? Thanks a lot in advance!
Here's my code:
LIVE DEMO
ID: <input formControlName="userid" type="text" pKeyFilter="num" placeholder="Numbers" pInputText>
There are many approaches to this problem. All of the provided solutions should work. My recommendation is Approach 2.
Approach 1
You can try to remove non number characters on the input event like this
<input
formControlName="userid"
type="text"
placeholder="Numbers"
oninput="javascript: this.value = this.value.replace(new RegExp('[^0-9]', 'gm'), '')"
pInputText
/>
Modified Demo
I tested this in Firefox and Chrome on MacOS and it seems to work fine.
Approach 2
To do this from your angular module:
Use a simple text input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
/>
Listen to changes and patch the value accordingly. Don't forget to register your observers on init.
registerChangeObservers() {
this.registrationFormGroup.get("userid").valueChanges.subscribe(val => {
this.registrationFormGroup.patchValue({
'userid': val.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
});
}
ngOnInit() {
this.registerChangeObservers();
}
Especially note the { emitEvent: false } part. You need to set this to avoid recursion. This approach can fail if your model becomes invalid and therefore it's value changes to nil. For example this can happen if you set your input type to number, but a user manages to input a non number character. To avoid this make sure the input validation doesn't fail on special characters, e.g. by setting the input type to text.
Demo here
Approach 3
To avoid the display of modifying characters you can also listen to input events (i.e. key presses) instead of actual value changes. This is equivalent to approach 1.
To do so use this input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
(input)="onPress($event)"
/>
and add this function to your controller
onPress($event) {
this.registrationFormGroup.patchValue({
'userid': $event.target.value.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
}
Demo 3
Note: I would generally avoid this approach because in my experience the suppression of modifying characters can have unintended side effects with some uncommon input methods, especially on mobile. The approach above (Approach 2) also works and is safer in my opinion. Although modifying characters are displayed, they will disappear on the next user action and will never be present in your model data.
You have already tried with:
<input type="number" pattern="[0-9]{10}" />
the following validates a 10-digit number, and I also think you should do a validation with JavaScript:
<input type="text" id="text" onblur="validaNumericos();" />
Function Javascript:
function validaNumericos(){
var inputtxt = document.getElementById('text');
var valor = inputtxt.value;
for(i=0;i<valor.length;i++){
var code=valor.charCodeAt(i);
if(code<=48 || code>=57){
inputtxt.value="";
return;
}
}
}
<input type="text" id="text" onblur="validaNumericos();" />
Use input type=number.
ID: <input formControlName="userid" type="number" pKeyFilter="num" placeholder="Numbers" pInputText>
If you don't like the dial controls on the right side, you can disable them with this in your css:
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type=number] {
-moz-appearance:textfield;
}
Here is a fork of your demo with all the changes.
Well, if you are looking for a regex answer (based on your tag), you can test on the length of the pre-regex value vs. the length of the post regex value.
if there are extra characters, the lengths will not match.
[0-9]+
Hi I have a number of inputs for telephone numbers, they use the same class and the same show/hide techinque.
I want to be able to clear the contents of the phone number in the input box, i.e. with the class name of input_tel.
However it seems to clear all inputs which I assume is because I am using the following line; input:text , when I put in a class it just fails to work.
My JS and some of my html is below or view a jsFiddle:
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).siblings('input:text').val('');
});
<div class="telephonetwo contact_numbers">
<input type="text" class="smallinput contactpagelabel" name="faxname" size="10" value="Fax">
<input type="checkbox" class="contact_no" name="showfax" value="Y">
<input type="text" name="fax" size="30" value="016128 13456" class="input_tel">
Hide Clear #
</div>
If you are viewing my JSfiddle click the reveal additional numbers for the clear button to appear.
Update
I want to be able to clear the closest input_tel rather than all of them, as their are multiple numbers.
Thanks in advance
replace:
$(this).siblings('input:text').val('');
with
$(this).siblings('input:text').closest('.input_tel').val('');
JSFIDDLE DEMO
How about targeting the input_tel class then?
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).parent().parent().find('input.input_tel').val('');
});
Assuming no other input fields have that input_tel class on them.
This should do it...
$(".contact_numbers").on('click', function () {
$(".input_tel").val('');
});
The safe way to clear input fields with jquery
$.fn.noText = function() {/*use the jquery prototype technology to make a chainable clear field method*/
if(this.is('input')){ /*check to c if you the element type is an input*/
this.val('');/*clear the input field*/
}return this;/*means it is chainable*/
};
$('input').noText();
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.