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.
Related
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 trying to allow Blank inputs on my form but also validate an email if ever the user inputs one, i already changed the regex several times with the ones that i find here in stackoverflow that allows blank input but all of them doesn't work
here is the original code:
['validate-email', {
errorMsg: Form.Validator.getMsg.pass('email'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]\.?){0,63}[a-z0-9!#$%&'*+\/=?^_`{|}~-]#(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\])$/i).test(element.get('value'));
}
}],
how can i allow my mootools form validator to accept blanks but also verify email if there is any input?
Direct Source:
http://mootools.net/docs/more/Forms/Form.Validator
I see two options.
Option 1
Remove the required class from the input element. That will accept an empty value but check/validate if not empty. Try it here.
Option 2
The one you already have :)
I normally use this regex:
/^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/i
Found also this one. Anyway, it works; check this demo.
Email validation regex is so clumsy... Does mootools support validation functions?
Anyway, you can take your regex and create a bit more clumsy one: original-regex|^$, which will accept empty string
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.
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.
So I have a form, but I don't need to be submitting the information to the server just yet... What I need, is to just run the fields through the HTML5 built-in validation conditions (such as email, etc.), and if true, just execute a specific function...
So far, I've come up with this...
function checkform()
{
var /* all the elements in the form here */
if (inputElement.validity.valid == 'false')
{
/* Submit the form,
this will cause a validation error,
and HTML5 will save the day... */
} else
{
navigateNextStep();
}
}
That's the logic I've come up with so far, and its a little backhanded because I'm submitting KNOWING that there's an invalid value, hence triggering the validation prompts...
My only problem with the above logic, is that I have about, 7-8 input elements, and I find the option of doing the following rather, 'dirty':
var inputs = document.getElementsByTagName("INPUT");
if (!inputs[0].validity.valid && !inputs[1].validity.valid && ...)
Ideas?
You can just call formEl.checkValidity()... This will return a boolean indicating whether or not the whole form is valid, and throw appropriate invalid events otherwise.
The spec
A brief JSFiddle to play with
I'm not sure how you're expecting submitting the form to trigger the browser's validation UI, though. Calling formEl.submit() seems to result in a submission regardless of the validation state. This is noted at the bottom of The H5F project page, which says:
Safari 5, Chrome 4-6 and Opera 9.6+ all block form submission until all form control validation
constraints are met.
Opera 9.6+ upon form submission will focus to the first invalid field
and bring up a UI block indicating
that it is invalid.
Safari 5.0.1, and Chrome 7 have removed form submission blocking if a
form is invalid, most likely due to
legacy forms now not submitting on
older sites.
Ok, so this is awkward... Thanks to Domenic, and good ol' Google, I came across an alternative solution...
I ran a for loop, checking if each of the input elements were valid or not through the imputElement.validity.valid method, which returned a boolean value...
For every element that was valid, I incremented a variable by 1, and included a conditional statement in the loop to check if the variable had been incremented enough to execute the navigation function...
If there was an invalid field, the if statement would never execute, and (here's the fun part) the browser would validate the fields anyways, pop up saying which fields were broken and needed user correction... :-)
The For Loop...
for (i=0;i<8;i++)
{
if (inputs[i].validity.valid)
hg++;
}
if (hg==8)
skimregform();
You can programmatically trigger the checking of each field in your form, even if you set event.preventDefault() function.
document.forms["form_id_name"].reportValidity();