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.
Related
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.
I have a website built on cherrypy which a user can submit some information via a form on one of the pages and then via javascript has some validation that the required fields are filled in. I was originally attempting to verify some integer only fields were indeed integers with something similar to this within my submit javascript before I passed it onto a python function to handle my db and other submissions.
$("#btnSubmit").click(function(){
$("#dlgmessage").html("Processing...");
$("#dialog-message").dialog("open");
var assigned_port = ($("#txtAssignedPort").val())
if(
Number.isInteger(assigned_port) === false
){
$("dlgmessage").html("Assigned Port is an Integer only field")
$("dialog-message").dialog("open");
document.getElementById('txtAssignedPort').style.borderColor = "red";
document.getElementById('txtAssignedPort_label').style.color = "red";
return;
}
<--snip-->
};
That was not working for me though as no matter my input it was always false even if all I entered was numbers.
So, I moved onto instead adding some additional pieces to my html files which define the form. Previously they would all look similar to:
<label id="txtAssignedPort_label" >Assigned Port (*)</label>
<input class="form-control" placeholder="Assigned Port (numbers only)" id="txtAssignedPort" value="${assigned_port}" />
I then added some additional attributes to the input element like so:
<label id="txtAssignedPort_label" >Assigned Port (*)</label>
<input class="form-control" type="number" step="1" min="0" max="65535" placeholder="Assigned Port (numbers only)" id="txtAssignedPort" value="${assigned_port}" maxlength="38" />
This then restricted the user from even typing any non number value. But, as explained in this stackoverflow post, Why does the html input with type "number" allow the letter 'e' to be entered in the field?, the number fields will accept 'e' as a value since it can accept floating point numbers.
Doesn't seem like a huge issue that it supports 'e' but then the issue arrives when I attempt to submit something with an e in the input. I added a simple line to my javascript console.log("ASSIGNED PORT = " + ($("#txtAssignedPort").val())); in order to view what the javascript was viewing the input as. This results in a console log of ASSIGNED PORT = 12345 when I do only numbers but as soon as I use an 'e' it instead shows ASSIGNED PORT = with no value defined for my input ($("#txtAssignedPort").val()))
While I don't expect users to ever really try and submit one with an e, I still want to cover my bases to make my inputs as clean as possible.
Why is it that my javascript views that input field as null once an 'e' character is included?
Is there a better way I should be trying to accomplish this, like with the javascript I had at first that was not working properly at the time?
I am having some problem in JavaScript form validation.
I have some optional fields in my HTML code. On submit, they don't need to be filled up but if the user provides some input they must be verified. For instance, I have an optional phone number field. If the user provides an input then I need to check if they are all numbers.
How could I do that?
You need only invoke the validation code if the field value meets some precondition, in this case: if the field has a value (checked by testing the length property of the string value):
var fieldValue = document.getElementById("someInput").value;
if( fieldValue.length > 0 ) {
if( someValidationFunction( fieldValue ) ) alert("Field is invalid");
}
What's stopping you from using HTML5's own validation?
<input type="tel" pattern="[0-9]+" />
No JavaScript required, will work on all modern browsers.
A note on security: Please don't rely on client-side validations for security concerns, as they can be trivially disabled. All validation should also be done server-side.
you can bind your custom method as a callback to your submit action in your form
<form onSubmit="return customValidation()>
In the method do your validations.
function customValidation()
{
//code to test fields
fieldToValidate = document.getElementById("field-id")
//validate the field
}
You can't use the other answers if you need it to be more secure; you shouldn't do this with JavaScript, because if a user for some reason has it turned off in their browser (or they turned it off on purpose) then the form won't still be verified. Instead you need to do it with PHP on the server. On the server that the form is being sent to you need to get the query strings sent with the form ($_GET['phonenumber'];), and see if it's a number (int intval ( mixed $phonenumber )). This should return NaN if it's not a number.
I'm trying to make a really basic anti-spam function where the script generates a random number and then the user has to type it in a text field in order for the form to validate. My problem is grabbing the value of the generated number to match it against the input. Here is how I generate the random number:
window.onload=function randomNumberGenerator()
{
var x=document.getElementById("number");
var randomNumber=Math.floor((Math.random()*100)+1);
x.innerHTML=randomNumber;
}
I was trying to get the number at validation like this:
var x=document.forms["contactForm"]["realPerson"].value;
var correct=document.getElementById("number").value;
if (x != correct)
{
alert("Please write in the correct number");
return false;
}
But after a while i realized that innerHTML doesn't put anything in the DOM that can be read (as least that seems to be the deal). So how can I retrieve that number to compare it when the form is submitted? I have thought about using a cookie, but that seemed a bit intimidating...
Thank you!
If you can access the generated number from client side, I think you lose the purpose. Better generate the random number in the server side and validate it after form submission .
You are going to just use innerHTML a second time, perhaps with a parseInt
var correct=parseInt(document.getElementById("number").innerHTML);
A checkbox will be created according to the query. I want to validate the checkbox before submitting the form.
I have used that check all and uncheck all using javascript so I used the attribute id in an array:
<input type="checkbox" name="playlist[]" id="playlist" value="<?php echo $filmpath; ?>"/>
I used the validation code as
//enter code here
function chkvalidate()
{
//enter code here
if ( document.modifyform.playlist.checked == false )
{
//enter code here
alert( "Please check the Terms & Conditions box." );
//enter code here
valid = false;
//enter code here
}
}
This code is not working.
Are you using the correct capitalisation in your code? JavaScript is case sensitive, and I believe that if you change modifyform to modifyForm your code will likely execute properly.
That being said, it is a good idea to use camelCase as a naming convention for your variable and function names. It is not required, but it makes for more consistent and easier to read code. Additionally, since any respectable third party library will be using camelCase, it will make it much easier for yourself if you use that convention as well, otherwise you will have multiple naming conventions throughout your source code, and that is simply not maintainable.
You need document.forms.modifyform.playlist.checked instead to access the form (by name or id) in the DOM. With your existing code, Javascript is trying to access a property called modifyform on the document object, which does not exist.
For reference, documentation.form shows the list of properties you can call on the form object.