I am trying to add some custom validations of allowing only number(amout) in the input boxes. As per the example given on here, I tried to add custom validation.
const onlyAmount = value => {
if (!value) return value
let onlyNums = value.replace(/^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/, '')
return onlyNums
}
and field of my final form is like
<Field
name="price"
component="input"
type="text"
parse={onlyAmount}
/>
No the problem, its not allowing me to add numbers properly. I read the docs of the but couldn't find any helping solution.
React Final Form : https://github.com/final-form/react-final-form
Any suggestions will be really helpful.
Add just type="number". The keyboard will not allow other than numbers.
type="hidden" seems like a mistake. Won't that result in a <input type="hidden"/>?
I have not mentally parsed your regex, but I'd recommend you try testing your parse function in that sandbox that you linked to and see why it's not working.
It's your regex. If you add a console to print out your value, then your onlyNum, you get empty string.
Related
EDIT:
So, after more playing the problem is a bit more complex than originally thought, and while I have found a workaround, I'm curious to figure out why this is happening, so here's the update:
I have created the following function to fill in form fields using HTML DOM:
function populateField(fieldname, value) {
document.getElementById(fieldname).value = value;
}
Then in the main part of my php code, I call that function and hand it the ID of the field, and the VALUE I want to set like this:
echo('<script>');
echo('populateField("contact", "'.$fillContact.'");');
echo('</script>');
This works perfectly fine for all my form fields except for the datetime-local field. It simply doesn't work.
So I decided to bypass my function, and just set the field directly in the main part of the code like this:
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
This works perfectly fine...but ONLY if I execute it before I call my function for the first time. In other words...
THIS works:
echo('<script>');
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
echo('populateField("contact", "'.$fillContact.'");');
echo('</script>');
but THIS does not work:
echo('<script>');
echo('populateField("contact", "'.$fillContact.'");');
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
echo('</script>');
For the life of me I can't figure out why it would make any difference at all, but there you have it. If anyone sees something that I'm missing, I would love to know what I'm doing wrong!
Thanks all!
ORIGINAL:
So this is an interesting one. I have an HTML form field with multiple fields, including a datetime-local field. Using Javascript I am able to access and/or change the value property of all of the other input fields using HTML DOM, but for some reason, I am unable to access or set the datetime-local value property. Trying to read the value of the field returns a value of "" and trying to set the value has no effect.
Interestingly, if I include the value="some datetime" into the HTML tag itself, it sets the value property correctly. Thinking the value="" may have been somehow mucking things up, I removed it, but there is no difference.
Here is the field code within the form:
<input type="datetime-local" name="arrival" id="arrival" value="'.date('Y-m-d').'T00:00">
That works correctly and sets the field to the current date with a time of 00:00:00.000.
But if I do something like this afterwords:
x = document.getElementById("arrival").value;
Then x = "";
Likewise, if I attempt to set the field by doing this:
document.getElementById("arrival").value = [some datetime value];
the field remains blank.
Obviously, I'm missing something here, but for the life of me I can't figure out what. I even went to lookup an example. This example works fine, but even copying the lines it still doesn't work in my code:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_datetime-local_value
Ideas?
I'm afraid your value for date is not in correct format. You need to have ISO-8601 formated date as mozilla references it in online docs here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';
Also, if you not set value and try to console it, it's empty as expected, and after you set it, it yields same date in ISO format.
GL
function myFunction() {
console.log( document.getElementById("myLocalDate").value )
}
Date: <input type="datetime-local" id="myLocalDate" value="">
<button onclick="myFunction()">Console date</button>
Basically I created a form in html and when things are input properly it simply goes to google.com. Right now I have completed the first few fields but I am unsure of how I would make it recognize if the input that was put in and did not include an # sign or a . some point after it.
I created a fiddle as I was having trouble getting some of the longer of my lines of code to be in-line.
Click here for the fiddle Example
You have a few options depending on how thorougly you want to validate.
email.indexOf('#') >= 0
checks that there is an # at all in the email. See http://jsfiddle.net/27f1h6ws/ for a version of your fiddle with it added.
A more thorough way would be to check it with regex. You can do it extremely simple just checking the general structure of the email input, or extremely thorough check for all valid characters, depending on how crucial the validation is. See this link or the answers in this question for more information.
You can use HTML5 properties like :
pattern attribute which contains a regexp
set your input type to email
If you want to do it with JavaScript, use a regexp also and use the test() method to verify it.
Add this
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
I'm using Twitter Bootstrap (v3) and I want to make a money input, where I can enter an amount of money with a fixed currency (currently €).
The input type needs to be type="number" because of how I want the input to look on mobile devices (not a big QWERTY keyboard, just numbers), but I do want to allow multiple patterns.
I think the way to go is with the .on("input", callback) method, but I'm not sure how to accomplish this.
I have tried the following:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
$(this).val($(this).val().replace(/[^0-9,\.]+/, ''));
});
});
(for the HTML and CSS, see the jsfiddle link)
But obviously that doesn't work, otherwise I wouldn't be posting here. Whenever you try to type something invalid, the whole string disappears.
http://jsfiddle.net/bjcayhzb/1/
Explanation rather than (or alongside) a working example highly is appreciated.
It is the type of input field 'number' that comes in the way. It has its own keyup/input handler attached (modern browsers deal with it via JS code too) and seems to break things.
If you use
<input type="text" required="" placeholder="42,00" class="form-control" id="amount" />
then this works:
$(document).ready(function() {
$("#amount").on("input", function() {
// allow numbers, a comma or a dot
var v= $(this).val(), vc = v.replace(/[^0-9,\.]/, '');
if (v !== vc)
$(this).val(vc);
});
});
The only drawback of this approach is that if you try to put bad character in the middle of the string, cursor jumps to the end. And, of course, you can type multiple dots and commas.
Better approach would be to keep last good value stored in data and test the whole string and replace if new character invalidates match for the whole string.
Update
When input type="number" value contains non-number, jQuery val() returns empty string. This is why your code is not working. If "number" is a must (e.g. for numeric mobile keyboard), an approach would be to keep last known correct val() and put it back into control.
JS Code:
I was using the following code for zip code validation for three countries USA/BR/CA.
/*To Get ZipCodeRegex as per country */
function getZipRegEx(inputcountry) {
var returntext;
if (inputcountry == "USA") {
returntext = /^\d{5}$/
}
else if (inputcountry == "CA") {
returntext = /^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1}$/
}
else if (inputcountry == "BR") {
returntext = /^([0-9]){5}([-])([0-9]){3}$/
}
return returntext;
};
Now, client has updated their code and using the MASK Plugin for input textbox. The mask pattern is rendering with data-mask attribute. Below is the rendered HTML for input control for zip code.
<input type="text" name="zip" id="zip" value="" class="required" data-mask="99999" />
Problem Area : Now with latest code base, they are covering more then 10 countries and each and every country/state is having different pattern for zip code.
So, is it possible to generate the regex pattern based on mask value coming with input field? This way, i need not to put the country specific checks.
Please suggest some implementation approach to cover this scenario.
Thanks in advance.
The MASK Plugin is already performing client-side validation of the entered ZIP code. That is what it is for. It doesn't make sense to duplicate that with your own client-side validation using Javascript.
Client side validation is just a convenience for the user anyway (reporting mistakes quickly so the user can correct them before the form is submitted); it never guarantees valid input, because it can be easily circumvented.
If you want to ensure good input, you must validate on the server side.
I'm sure there must be a simple solution to this..
I simply want to create a rudimentary human verification tool for an online form. In pseudo-code, something like
$answer = "foo";
if (form['question'] == $foo){
// Proceed
} else {
// Fail
}
The jQuery docs seem to have an equalTo method but this is to compare a form field with another form value..
Any tips greatly appreciated! :)
You need to have a look at JQuery Validation plugin at http://docs.jquery.com/Plugins/validation. Consider the following example:
You may change the rules as explained in the plugin to implement your custom validations.
Have you looked at this plugin? You can use it to make fields required, validate for certain value types (number, string, credit card, etc), and I believe you can write callback functions to validate for specific values.
http://docs.jquery.com/Plugins/validation
var answer = 'foo';
if ($('#question').val() == answer) {
// Proceed
} else {
// Fail.
}